参考文章:
知乎:Webpack 大法之 Code Splitting
来源项目:
vue-element-admin
RuoYi
下图左侧为为分割的打包,右侧为分割的打包,很明显的看出,右侧将element和echarts这两个比较大的包从其中分离出来:
而这种做最直接明显的优势就是,像element及echarts这种很大的文件,在很大的情况下是不会改变内容的,比如我们在一个页面的功能修改了一下,打包上传,如果未分割的打包,浏览器会发现这个js文件有变动了,就会重新加载很大的几百KB甚至上M的js文件,但是将这些不会变动的包分割出来,就会像下图所示,直接调用缓存,而不是再次重新加载:
具体实现方法是采用vue.config.js里的配置,如下:
module.exports = {
// ...
config
.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
libs: {
name: 'chunk-libs',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial' // only package third parties that are initially dependent
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
},
echarts: {
name: 'chunk-echarts', // split echarts into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?echarts(.*)/ // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: