gulp构造小型项目小记

现在正在开辟一个python markdown wiki体系,关于前端模块化与打包这块涌现了一些挑选。
1、采纳webpack模块化及打包
因为项目比较小,轻微相识后,以为没必要采纳webpack。杀鸡焉用牛刀?
2、采纳requirejs模块化,gulp打包
照样因为项目比较小,以至不须要举行模块化,所以摒弃采纳requirejs,只是采纳gulp举行打包。
3、css预编译框架,现在比较盛行的有sass,less:现在没有采纳,下一步尝试一下。
4、js组件化,现在比较盛行的如Angular,VueJs等。项目较小,须要ajax交互更新页面的并不多,没有采纳。部份功能用模板引擎的宏来完成。

固然采纳gulp打包重要是为相识决以下几个题目:
1、js、css文件紧缩与兼并
2、js、css缓存与版本题目

关于js、css缓存与版本题目题目,现在为处理新版本宣布,使得浏览器缓存发送新的要求而不是运用缓存的js,css文件。有两种计划:

  • app.js变成app-2qwee.js

  • app.js变成app.js?v=wqe2434er3

我比较喜好的是后者体式格局。
gulp有个插件gulp-version-number能够处理这个题目,然则因为我采纳模板引擎jinja2与flask框架开辟,所以html中是如许的

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='app.css') }}">

经由gulp-version-number编译后变成了

<link rel="stylesheet" type="text/css" href="{{ url_for('?v=16124df4fdca2e5244636c2bca625276static', filename='app.css') }}">

而我希冀的是

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='app.css') }}?v=16124df4fdca2e5244636c2bca625276">

猎奇的你肯定会问,为何希冀的不是如许呢?
url_for(‘static’, filename=’app.css?v=16124df4fdca2e5244636c2bca625276′) }}”
经试验,经由url_for输出效果中?变成了%3F,经由了urlencode,所以浏览器没法辨认它为查询参数。

没办法,只能改改这个插件的源码:详细代码在插件代码的index.js处:大概在207-284行部份:
重要修改就是替代sts[i].match正则,到场_RULE长度推断。

   var appendto = {
        'css': function (content, k, v) {
            var sts = content.match(/<link[^>]*rel=['"]?stylesheet['"]?[^>]*>/g);
            
            if (util.isArray(sts) && sts.length) {
                for (var i = 0, len = sts.length; i < len; i++) {
                    
                    //var _RULE = sts[i].match(/href=['"]?([^>'"]*)['"]?/);
                    var _RULE=sts[i].match(/(\{\{\surl_for\('static',\s?filename=['"].*?['"]\s?\)\s\}\})/);
                    if(!_RULE||_RULE.length<2){
                        continue;
                    }
                    console.log(sts[i]);
                    console.log(_RULE[1]);
                    if (_RULE[1]) {
                        var _UrlPs = parseURL(_RULE[1]);
                        var _Query = queryToJson(_UrlPs.query);
                        var _Append = {};
                        if (!_Query.hasOwnProperty(k) || this['cover']) {
                            _Append[k] = v;
                        }
                        _UrlPs.query = jsonToQuery(util._extend(_Query, _Append));
                        content = content.replace(sts[i], sts[i].replace(_RULE[1], renderingURL(_UrlPs)));
                    }
                }
            }
            return content;
        },
        'js': function (content, k, v) {
            var sts = content.match(/<script[^>]*src=['"]?([^>'"]*)['"]?[^>]*>[^<]*<\/script>/g);
            if (util.isArray(sts) && sts.length) {
                for (var i = 0, len = sts.length; i < len; i++) {
                    var _RULE = sts[i].match(/(\{\{\surl_for\('static',\s?filename=['"].*?['"]\s?\)\s\}\})/);//.match(/src=['"]?([^>'"]*)['"]?/);
                    if(!_RULE||_RULE.length<2){
                        continue;
                    }
                    console.log(sts[i]);
                    console.log(_RULE[1]);
                    
                    if (_RULE[1]) {
                        var _UrlPs = parseURL(_RULE[1]);
                        var _Query = queryToJson(_UrlPs.query);
                        var _Append = {};
                        if (!_Query.hasOwnProperty(k) || this['cover']) {
                            _Append[k] = v;
                        }
                        _UrlPs.query = jsonToQuery(util._extend(_Query, _Append));
                        content = content.replace(sts[i], sts[i].replace(_RULE[1], renderingURL(_UrlPs)));
                    }
                }
            }
            return content;
        },
        'image': function (content, k, v) {
            var sts = content.match(/<img[^>]*>/g);
            if (util.isArray(sts) && sts.length) {
                for (var i = 0, len = sts.length; i < len; i++) {
                    var _RULE = sts[i].match(/(\{\{\surl_for\('static',\s?filename=['"].*?['"]\s?\)\s\}\})/);//.match(/src=['"]?([^>'"]*)['"]?/);
                    if(!_RULE||_RULE.length<2){
                        continue;
                    }
                    console.log(sts[i]);
                    console.log(_RULE[1]);
                    if (_RULE[1]) {
                        var _UrlPs = parseURL(_RULE[1]);
                        var _Query = queryToJson(_UrlPs.query);
                        var _Append = {};
                        if (!_Query.hasOwnProperty(k) || this['cover']) {
                            _Append[k] = v;
                        }
                        _UrlPs.query = jsonToQuery(util._extend(_Query, _Append));
                        content = content.replace(sts[i], sts[i].replace(_RULE[1], renderingURL(_UrlPs)));
                    }
                }
            }
            return content;
        }
    };

然后,项目重要设置文件以下:不多说,详细看设置
package.json

{
  "name": "mdwiki",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "xbynet",
  "license": "ISC",
  "devDependencies": {
    "del": "^2.2.2",
    "gulp": "^3.9.1",
    "gulp-autoprefixer": "^3.1.1",
    "gulp-clean": "^0.3.2",
    "gulp-concat": "^2.6.1",
    "gulp-flatten": "^0.3.1",
    "gulp-minify-css": "^1.2.4",
    "gulp-rev": "^7.1.2",
    "gulp-sourcemaps": "^1.9.1",
    "gulp-uglify": "^2.0.0",
    "gulp-version-number": "^0.1.5",
    "pump": "^1.0.1",
    "run-sequence": "^1.2.2"
  }
}

gulpfile.js

const gulp = require('gulp');
const uglify = require('gulp-uglify');
const pump = require('pump');
const version = require('gulp-version-number');
const autoprefixer = require('gulp-autoprefixer');
const sourcemaps=require('gulp-sourcemaps');
const runSequence = require('run-sequence');
const del = require('del');
const cssmin = require('gulp-minify-css');
//const imagemin = require('gulp-imagemin');
const clean = require('gulp-clean');
//const flatten = require('gulp-flatten');
const DEST_DIR='build';
const SRC_DIR='mdwiki-master/app';
// Environment setup.
var env = {
    production: false
};

// Environment task.
gulp.task("set-production", function(){
    env.production = true;
});

const versionConfig = {
  'value': '%MDS%',
  'append': {
    'key': 'v',
    'to': ['css', 'js','image'],
  },
};

gulp.task('html',()=>{
    return gulp.src(SRC_DIR+'/**/*.html')
    .pipe(version(versionConfig))
    .pipe(gulp.dest(DEST_DIR));
});
gulp.task('jsmin', function (cb) {
    if(env.production){
        return gulp.src([SRC_DIR+'/**/*.js'])
        .pipe(uglify({mangle: {except: ['require' ,'exports' ,'module' ,'$']}})) //消除殽杂关键字
        .pipe(gulp.dest(DEST_DIR));
    }
    else{
        return gulp.src([SRC_DIR+'/**/*.js'])
        .pipe(sourcemaps.init())
        .pipe(uglify({mangle: {except: ['require' ,'exports' ,'module' ,'$']}})) //消除殽杂关键字
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(DEST_DIR));
    }
    
});
gulp.task('cssmin', function () {
    if(env.production){
        return gulp.src(SRC_DIR+'/**/*.css')
        //.pipe(concat('main.css'))
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(cssmin())
        .pipe(gulp.dest(DEST_DIR));
    }
    else{
        return gulp.src(SRC_DIR+'/**/*.css')
        //.pipe(concat('main.css'))
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(sourcemaps.init())
        
        .pipe(cssmin())
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(DEST_DIR));
    }
    
});
gulp.task('rawtoone', () =>{
    return gulp.src([SRC_DIR+'/**/*.{png,jpg,jpeg,gif,bmp,ico}',SRC_DIR+'/**/*.{swf,eot,svg,ttf,woff}'])
        .pipe(flatten())
        //.pipe(imagemin())
        .pipe(gulp.dest(DEST_DIR));
    }
);
gulp.task('copy', () =>{
    return gulp.src([SRC_DIR+'/**/*.{png,jpg,jpeg,gif,bmp,ico}',SRC_DIR+'/**/*.{swf,eot,svg,ttf,woff}'])
        .pipe(gulp.dest(DEST_DIR));
    }
);
// Clean
gulp.task('clean', function(cb) {
   return  del(['./build'],cb);
      // return gulp.src('build', {read: false,force: true})
      //  .pipe(clean());
});
// Default task
gulp.task('dev',function(callback) {
    runSequence('clean',['html', 'jsmin','cssmin','copy'],callback);
});

gulp.task('product',function(callback) {
    runSequence('set-production','clean',['html', 'jsmin','cssmin','copy'],callback);
});
gulp.task('watch', function() {
  gulp.watch(SRC_DIR+'/**/*.html',['html']);
  gulp.watch(SRC_DIR+'/**/*.js', ['jsmin']);
  gulp.watch(SRC_DIR+'/**/*.css', ['cssmin']);
  gulp.watch([SRC_DIR+'/**/*.{png,jpg,jpeg,gif,bmp,ico}',SRC_DIR+'/**/*.{swf,eot,svg,ttf,woff}'],['copy']);
  // Create LiveReload server
  //livereload.listen();
  // Watch any files in dist/, reload on change
  //gulp.watch(['dist/**']).on('change', livereload.changed);
});
    原文作者:xbynet
    原文地址: https://segmentfault.com/a/1190000007613571
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞