如何加快webpack构建?

时间:2016-08-04 14:29:14

标签: node.js gruntjs webpack uglifyjs

我正在使用webpack捆绑JavaScript文件并使用uglify插件来缩小它们。缩小步骤需要比预期更长的时间并使该过程变长。有没有办法改善webpack的缩小时间(uglify插件)?

这是我的webpack配置:

/*jslint node: true */
var webpack = require("webpack"),
    _ = require("lodash"),
    path = require("path"),
    fs = require("fs"),
    webpackConfig,
    commonsPlugin = new webpack.optimize.CommonsChunkPlugin('m-common-[chunkhash:8].js'),
    dedupePlugin = new webpack.optimize.DedupePlugin(),
    uglifyPlugin = new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        },
        output: {
            comments: false,
        }
    }),
    sourceMapPlugin = new webpack.SourceMapDevToolPlugin('[file].map', null,
                                                         '[absolute-resource-path]',
                                                         '[absolute-resource-path]'),

    fnCaseSensitivityPlugin = function () {
        this.plugin('normal-module-factory', function(nmf) {
            nmf.plugin('after-resolve', function(data, done) {
                var parentDir = path.dirname(data.resource);
                var resourceName = path.basename(data.resource);
                fs.readdir(parentDir, function(err, files) {
                    if (err) {
                        done(err);
                    }
                    if (files.indexOf(resourceName) === -1) {
                        var realName = _.find(files, function(filename) {
                            return filename.toLowerCase() === resourceName.toLowerCase();
                        });
                        done(new Error('CaseSensitivityPlugin: `' + resourceName + '` does not match the corresponding file on disk `' + realName + '`'));
                        return;
                    }
                    done(null, data);
                });
            });
        });
    },

    fnDonePlugin = function () {
        this.plugin("done", function(stats) {
            var statsByChunk = JSON.parse(JSON.stringify(stats.toJson())).assetsByChunkName;
            webpackConfig.statsByChunk = statsByChunk;

            for (var chunkName in statsByChunk) {
                if (statsByChunk.hasOwnProperty(chunkName)) {
                    var nameIn = statsByChunk[chunkName][0],
                        gzName = nameIn.substring(0, nameIn.length - 2) + "gz.js";
                    webpackConfig.filesToCompress['./jaga-web/dist/' + gzName] = './jaga-web/dist/' + nameIn;

                    // The mrvlBuildOut object contains a set of name/value
                    // pairs to be used during HTML template processing.
                    // There are certain filenames we need to add to the
                    // mrvlBuildOut object as properties so that they can be
                    // injected into HTML templates that make use of them.
                    // The code below takes the nameIn string which will have
                    // one of 2 forms:
                    //
                    //      Debug Builds:
                    //          m-core-fixed.js
                    //
                    //      Produciton Builds:
                    //          m-core-<chunkid>.js
                    //
                    // It strips off everything after the last dash including the
                    // .js extension so we are left with the base filename. We then
                    // use that filename base to look up the name of the property
                    // we should set to that filename on the mrvlBuildOut object.

                    var map = webpackConfig.mrvlBuildOutFilePropMap,
                        propName = map[nameIn.replace(/-[^-]+\.js$/ , '')];

                    if (propName) {
                        webpackConfig.mrvlBuildOut[propName] = nameIn;
                    }
                }
            }

            webpackConfig.webpackDoneListeners.forEach(function (fnCall) {
                fnCall(statsByChunk);
            });
        });
    };

webpackConfig = {

    mrvlBuildOut: {
        //gets filled in with m-common-[chunkhash] and m-web-[chunkhash]
    },

    mrvlBuildOutFilePropMap: {
        "m-common": "jagacommon",
        "m-web":    "jagaweb",
        "m-blog":   "jagablog",
        "m-gallery":   "jagagallery",
        "m-landing":   "jagalanding",
        "m-unsupported": "jagaunsupported",
        "m-login":   "jagalogin",
        "m-voice-chrome":   "voicechrome",
        "m-apps-chrome":   "appschrome",
        "m-viewpage-chrome": "viewpagechrome"
    },

    webpackDoneListeners: [],
    filesToCompress: {
    },

    jaga: {
        addVendor: function (name, path, noparse) {
            this.resolve.alias[name] = path;
            if (noparse) {
                this.module.noParse.push(new RegExp(path));
            }
            this.entry.vendors.push(name);
        },

        addBuildOutFilePropMapEntry: function( filenameBase, propName ) {
            if ( filenameBase && propName ) {
                webpackConfig.mrvlBuildOutFilePropMap[filenameBase] = propName;
            }
        },

        stats: {
            colors: true,
            modules: true,
            reasons: false
        },
        entry: {
            'm-web': './jaga-web/js/app.js',
            'm-blog': './jaga-web/js/app-blog.js',
            'm-gallery': './jaga-web/js/app-gallery.js',
            'm-landing': './jaga-web/js/app-landing.js',
            'm-unsupported': './jaga-web/js/app-unsupported.js',
            'm-login': './jaga-web/js/app-login.js',
            'm-voice-chrome': './jaga-web/js/app-voice-chrome.js',
            'm-apps-chrome': './jaga-web/js/app-apps-chrome.js',
            'm-viewpage-chrome': './jaga-web/js/app-viewpage-chrome.js',
            vendors: []
        },
        resolve: {
            modulesDirectories: [
                'node_modules',
                'jaga-web',
                'jaga-web/js'
            ],
            alias: {
                // If you find yourself wanting to add an alias here, think
                // about if it would be better for your component to live in
                // jaga-core instead of in jaga-web. See the README.md in
                // jaga-core for more info.
                'jaga-apps': __dirname + '/jaga-web/js/apps.js',
                'uuid': 'node-uuid'
            }
        },
        output: {
            path: 'jaga-web/dist',
            filename: '[name]-[chunkhash:8].js',
            chunkFilename: '[name]-[chunkhash:8].js'
        },
        module: {
            noParse: [
                /[\/\\].html$/
            ]
        },
        plugins: [
            commonsPlugin,
            dedupePlugin,
            uglifyPlugin,
            fnCaseSensitivityPlugin,
            sourceMapPlugin,
            fnDonePlugin
        ]
    }
};

var libs_dir = __dirname + '/jaga-core/src/js/lib/';
webpackConfig.jaga.addVendor("jquery", libs_dir + "jQuery/jquery.min.js", true);
webpackConfig.jaga.addVendor("lodash", libs_dir + "lodash/lodash.min.js", true);
webpackConfig.jaga.addVendor("underscore", libs_dir + "lodash/lodash.min.js", true);
webpackConfig.jaga.addVendor("q", libs_dir + "q/q.js", true);
webpackConfig.jaga.addVendor("backbone", libs_dir + "backbone/backbone-min.js", false);//if we don't parse backbone then require is not found??
webpackConfig.jaga.addVendor("cookie", libs_dir + "cookie/cookie.js", true);
webpackConfig.jaga.addVendor("canvas-to-blob", libs_dir + "canvas-to-blob/canvas-to-blob.js", true);

webpackConfig.jagaDebug = {
    watch: true,
    keepAlive: true,
    stats: webpackConfig.jaga.stats,
    entry: webpackConfig.jaga.entry,
    resolve: webpackConfig.jaga.resolve,
    output: {
        path: 'jaga-web/dist',
        filename: '[name]-fixed.js',
        chunkFilename: '[name]-fixed.js'
    },
    module: webpackConfig.jaga.module,
    //devtool: "eval-source-map",
    //devtool: "source-map",
    devtool: "eval",
    addBuildOutFilePropMapEntry: webpackConfig.jaga.addBuildOutFilePropMapEntry,
    plugins: [
        commonsPlugin,
        dedupePlugin,
        fnCaseSensitivityPlugin,
        sourceMapPlugin,
        fnDonePlugin
    ]
};
webpackConfig.jagaDebug.output.pathinfo = true;

module.exports = webpackConfig;

我正在使用grunt-webpack npm包。这是我对webpack的Gruntfile配置

 webpack: {
            test: appsConfig.augmentWebpackConfig(webpackConfig.jaga),
            jagaDebug: appsConfig.augmentWebpackConfig(webpackConfig.jagaDebug)
        },

请注意,webpackConfig引用上面的配置文件。

0 个答案:

没有答案