有时候对于多次重复引入的第三方和公共模块,我们可以单独打包成chunk,然后在各个文件内引入公共的chunk
optimization: {// 代码分割splitChunks: {chunks: 'all',// 缓存分组cacheGroups: {vendor: {name: 'vendors', // chunk名称priority: 1, // 权限更高,优先抽离test: /node_modules/,minSize: 0, // 大小限制minChunks: 1 // 最少复用过几次},common: {name: 'common', // chunk名称priority: 0,minSize: 0, // 公共模块的大小限制minChunks: 2 // 公共模块最少复用过几次}}}}
这样做可以让公共的,第三方包打在同一个代码块内,其他需要的地方直接引用该模块,不需要重复打包。对于多入口打包形成的html配置如下:
plugins: [new HtmlWebpackPlugin({template: path.join(srcPath, 'index.html'),filename: 'index.html',// chunks 表示该页面要引用哪些 chunk (即上面的index和other)chunks: ['index', 'vendors', 'common'] // 引入vendors 和 common}),new HtmlWebpackPlugin({template: path.join(srcPath, 'other.html'),filename: 'other.html',chunks: ['other', 'vendors', 'common'] // 名字与上面的name对应})]
