将Gulp任务转换为webpack

时间:2016-08-26 03:43:09

标签: angularjs gulp webpack

主要任务:

  • 将“按顺序”连接js文件并缩小
  • minify不应该破坏角度js模块
  • 输出js文件名应该带有md5字符串以防止浏览器的缓存。例如。 bundle-24141asd.js
  • 生成的js bundle-24141asd.js将更新为index.html

JS

    'use strict';

    var concatFile = require('gulp-concat'),
        gulp = require('gulp'),
        minifyCss = require('gulp-minify-css'),
        concat = require('gulp-concat'),
        shell = require('gulp-shell'),
        amdOptimize = require('amd-optimize'),
        print = require('gulp-print'),
        usemin = require('gulp-usemin'),
        uncache = require('gulp-uncache'),
        rev = require('gulp-rev'),
        revCollector = require('gulp-rev-collector'),
        rename = require("gulp-rename"),
        sourcemaps = require('gulp-sourcemaps'),
        ngAnnotate = require('gulp-ng-annotate'),
        clean = require('gulp-clean'),
        revDel = require('rev-del'),
        gutil = require('gulp-util'),
        wait = require('gulp-wait'),
        runSequence = require('run-sequence'),
        fs = require('fs'),

    var css_assets = [
        "./css/*.css",
    ];

    var general_js_assets = [];

    var ng_js_list = [
        "js/jquery-1.11.2.min.js",
        "js/common_scripts_min.js",
        "assets/validate.js",
        ".//bower_components/angular/angular.min.js",
        ".//bower_components/angular-messages/angular-messages.min.js",
        ".//bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js"
    ]

    gulp.task('process_ng_js', function() { //- 创建一个名为 concat 的 task
        var stream = gulp.src(ng_js_list) //- 需要处理的css文件,放到一个字符串数组里
        // .pipe(ngAnnotate())
        // .pipe(uglify())
        .pipe(sourcemaps.init())
        .pipe(concat('ng_required.min.js')) //- 合并后的文件名
        .pipe(rev()) //- 文件名加MD5后缀
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dist/js')) //- 输出文件本地
        .pipe(rev.manifest()) //- 生成一个rev-manifest.json
        .pipe(rename({
            prefix: "ng-js-",
        }))
        .pipe(gulp.dest('./dist'));
        return stream;
    });


    gulp.task('concat_css', function() { //- 创建一个名为 concat 的 task
        var stream = gulp.src(css_assets) //- 需要处理的css文件,放到一个字符串数组里
            .pipe(concat('app.min.css')) //- 合并/**后的文件名
            .pipe(minifyCss({options: {
                // processImport: false
            }})) //- 压缩处理成一行
            .pipe(rev()) //- 文件名加MD5后缀
            .pipe(gulp.dest('./dist/css')) //- 输出文件本地
            .pipe(rev.manifest()) //- 生成一个rev-manifest.json
            .pipe(rename({
                prefix: "css-",
            }))
            .pipe(gulp.dest('./dist')); //- 将 rev-manifest.json 保存到 rev 目录内
        return stream;
    });

    gulp.task('clean', function () {
      var stream = gulp.src(['./dist/js/*.js', './dist/js/*.js.map', './dist/js/required_lib*'], {read: false})
      var stream = gulp.src(['./dist/js/app*.js',
        './dist/js/app*.js.map',
         // './dist/css/**/*'
         ],
         {read: false})
        .pipe(clean({force: true}));
      return stream;
    });

    gulp.task('update_revision', function() {
        gulp
        .src(['./dist/*.json', './portal/index_tpl.html']) //- 读取 rev-manifest.json 文件以及需要进行css名替换的文件
        .pipe(revCollector({replaceReved: true})) //- 执行文件内名的替换
        .pipe(rename({
            basename: "index",
            extname: ".html"
        }))
        .pipe(gulp.dest('./portal')); //- 替换后的文件输出的目录
    });

    gulp.task('revision_portal_page', function() {
        gulp
        .src(['./dist/*.json', './index.tmpl.html']) //- 读取 rev-manifest.json 文件以及需要进行css名替换的文件
        .pipe(revCollector({replaceReved: true})) //- 执行文件内名的替换
        .pipe(rename({
            basename: "index",
            extname: ".html"
        }))
        .pipe(gulp.dest('./')); //- 替换后的文件输出的目录
    });

    gulp.task('default', function(callback) {
      return runSequence(
        'clean',
        [
            'process_ng_js',
            'process_ng_app'
        ],
        // ['process_ng_js','process_ng_app'],
        ['concat_css'],
        'update_revision',
        'revision_portal_page',
        callback
      );
    });

    var js_watcher = gulp.watch(['./app/main/*.js', './app/index**.js']
        , ['default']);
    js_watcher.on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

    var css_watch = gulp.watch(['.//css/style.css']
        , ['default']);
    css_watch.on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

    var html_watcher = gulp.watch(['index.tmpl.html',
        'tour_package.html',

        ],
        ['default']); html_watcher.on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

Webpack(待完成)

    var path = require('path');
    var webpack = require('webpack');

    module.exports = {
        entry: [
            './index.js'
        ],
        output: {
            path: __dirname, 
            filename: 'bundle.js' // <- could I make it with MD5 string(to invalidate brwoser cache) and update it into index.html ?
        },
        devtool: 'source-map',
        module: {
            loaders: [
                {
                    test: /\.jsx?$/,
                    loader: 'babel-loader',
                    exclude: /node_modules/,
                    query: {
                        presets: ['es2015', 'react']
                    }
                }
            ]
        }
    };

2 个答案:

答案 0 :(得分:0)

您需要在输出文件中添加webpack提供的[hash]选项,因此这将启用长期缓存。

    {
    output: {
        path: __dirname, 
        filename: "bundle-[hash].js",
    }
}

答案 1 :(得分:0)

webpack已捆绑您的文件,这意味着连接。此外,如果将输出部分设置为:

,它会将哈希添加到捆绑文件中
output: {
  path: __dirname, 
  filename: 'bundle-[chunkhash].js'
}

对于minify和mangle操作,您可以使用webpack plugins。例如,你可以在下面:

new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        },
        minimize: true,
        mangle: {except: ["myModule1", "myModule2"]}

为了不破坏您的模块,您可以将它们添加到 mangle.except 数组中,如上所述。

额外信息,如果您想拥有将捆绑文件名映射到散列捆绑文件名的清单文件,以便进一步使用,您可以添加:

new Manifest({
  fileName: "bundles" + ".manifest.json"
})

但你需要通过npm安装它。