Webpack:如何使用CommonsChunkPlugin将条目捆绑到多个常见块?

hgu*_*ser 14 javascript webpack

假设我有两个页面,Page1并且Page2它们都使用了一些库(供应商)jquery backbone,我希望将其作为单个文件提取出来,然后我希望将共享模块(不包括供应商)提取到另一个文件中,这就是webpack配置:

function listFiles(srcpath) {
    return fs.readdirSync(srcpath).filter(function (file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}
var createEntry = function (src) {
    var dest = {
        vendor: ["backbone", "underscore"]
    };
    var files = listFiles(src);
    files.forEach(function (dir) {
        var name = dir;
        dest[name] = src + "/" + dir + "/entry.js";
    });
    return dest;
};

//each sub directory contains a `entry.js` as the entry point for the page
var entries = createEntry("./app/pages");//    {vender:['jquery','backbone'],page1:'src/page1/entry.js',page2:'src/page2/entry.js'    }

var config = {
    resolve: {
        root: path.resolve('./app/'),
        extensions: ['', '.js']
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'common',
            filename: 'common.js',
            minChunks: 2
        })
    ],
    entry: entries,
    output: {
        path: './../main/webapp/static/dist',
        filename: '[name].js',
        publicPath: '/static/dist'
    }
};
module.exports = config;
Run Code Online (Sandbox Code Playgroud)

但是使用上面的配置:

common.js 包含webpack运行时,

page1.js 包含page1指定的模块和共享模块

page2.js 包含page2指定的模块和共享模块

这意味着page1.jspage2.js包含了太多的重复代码.

然后我尝试更改配置:

var entries = createEntry("./app/pages");
var chunks = [];
for (var k in entries) {
    if (k === 'vendor')
        continue;
    chunks.push(k);
}


new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),
new webpack.optimize.CommonsChunkPlugin({
    name: 'common',
    filename: 'common.js',
    minChunks: 2,
    chunks:chunks
}),
Run Code Online (Sandbox Code Playgroud)

然后

common.js 包含webpack运行时和供应商库以及共享模块

vendor.js 包含webpack运行时和供应商库.

page1.js 包含page1指定的模块

page2.js 包含page2指定的模块

它似乎越来越近了,但不common.js应该包含供应商

哪里不对了?

nga*_*ull 13

如果您需要多个公共块包,则必须为每个公共包指定所有块详细信息,如示例中所示:

var config = {

    entry: {
        vendor: ["backbone", "underscore"],
        common: "./app/pages/common/entry.js",
        page1: "./app/pages/page1/entry.js",
        page2: "./app/pages/page2/entry.js"
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendor",
            chunks: ["vendor"]
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "common",
            chunks: ["common"]
        })        
    ]
};
Run Code Online (Sandbox Code Playgroud)

请注意,chunks选项是CommonsChunkPlugin指您定位的条目的名称.当你想要拆分vendorcommon,你必须明确地说你只想vendor进入vendorcommon-chunk并且相同common.