我正在使用WebPack CommonsChunkPlugin提取重复代码并减少 JavaScript 代码大小。我有两个 html 页面和两个条目。我还添加了ReactJs供应商条目。到目前为止,在webpack.config.js我们有:
var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
context: __dirname,
entry: {
react: ["react", "react-dom"],
home: './assets/js/home.jsx',
about: './assets/js/about.jsx',
},
output: {
path: path.resolve('./assets/bundles/'),
filename: "[name].js",
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
new webpack.optimize.CommonsChunkPlugin({
name: 'react',
minChunks: Infinity
}),
new BundleAnalyzerPlugin(),
],
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
plugins: [["lodash", { "id": ["semantic-ui-react"] }]],
presets: ["es2015", "react"]
}
},
],
},
resolve: {
modules: ['node_modules', 'bower_components'],
extensions: ['*', '.js', '.jsx']
},
};
此配置结果与webpack-bundle-analyzer:
如您所见,有一些重复的代码,一些在红色区域,另一些在绿色区域。我想从家中提取这个 js 代码并将包提取到一个单独的包中。为了提取红色区域代码,即lodash库,我在 webpack 配置中添加了这些行:
new webpack.optimize.CommonsChunkPlugin({
name: 'lodash',
minChunks: function(module, count) {
return module.context.indexOf('node_modules/lodash') >= 0;
}
}),
但它没有按预期工作,lodash 库代码仍然在 home 和 about bundles 中,webpack 还创建了一个名为 lodash 的 bundle,它几乎是空的并且不包含任何 js 库。
关于如何解决它的任何想法?提取绿色代码怎么样?