防止重复的两种配置方法
1.配置dependOn
const path = require('path');
module.exports = {
mode: 'development',
entry: {
index: {
import: './src/index.js',
dependOn: 'shared',
},
another: {
import: './src/another-module.js',
dependOn: 'shared',
},
shared: 'lodash',
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
optimization: {
runtimeChunk: 'single',
},
};
可以看到dist目录下生成的文件,index.bundle.js和another.bundle.js以来的lodash被分离出来到shared.bundle.js
配置:
optimization: {
runtimeChunk: 'single',
},
会有runtime.bundle.js生成,官网的解释是为了避免这里的麻烦
2.SplitChunksPlugin插件
const path = require('path');
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
another: './src/another-module.js',
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
};
dist目录下会生成如下文件,lodash被分离到vendors-node_modules_lodash_lodash_js.bundle.js文件中