①. vue-router使用懒加载.
②. 按需引用组件库、UI库,避免全局注入.
③. 使用SplitChunks分离代码并实现相同模块共享,从而减少请求次数.
(1). 打包工具分析:
①. 通过可视化分析页面报告:
a. 上图会了多个chunk包,导致有大概300个请求.
(2). 配置SplitChunks对注意模块进行分离:
chainWebpack: config => {
if (!DEV) {
config.optimization.splitChunks({
cacheGroups: {
common: {
name: 'chunk-common', // 打包后的文件名
chunks: 'all',
minChunks: 2,
maxInitialRequests: 5,
minSize: 0,
priority: 1,
reuseExistingChunk: true
},
vendors: {
name: 'chunk-vendors',
test: /[\\/]node_modules[\\/]/,
chunks: 'all',
priority: 2,
reuseExistingChunk: true,
enforce: true
},
ElementUI: {
name: 'chunk-element-ui',
test: /[\\/]node_modules[\\/]element-ui[\\/]/,
chunks: 'all',
priority: 3,
reuseExistingChunk: true,
enforce: true
},
xlsx: {
name:"chunk-xlsx",
test: /[\\/]node_modules[\\/]xlsx[\\/]/,
chunks: 'all',
priority: 4,
reuseExistingChunk: true,
enforce: true
}
}
})
}
}
(3). 优化后打包工具分析:
①. 通过可视化分析页面报告,明显生成的chunk包比上图要少,差不多130多个请求.
花裤衩vueconfig.js已经配置好了,如下为去掉配置前后对比,可能是项目小,打包效果不太明显.
(1). vueconfig.js:
module.exports = {
chainWebpack(config) {
config
.when(process.env.NODE_ENV !== 'development',
config => {
config
.plugin('ScriptExtHtmlWebpackPlugin')
.after('html')
.use('script-ext-html-webpack-plugin', [{
// `runtime` must same as runtimeChunk name. default is `runtime`
inline: /runtime\..*\.js$/
}])
.end()
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
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true
}
}
})
// https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
config.optimization.runtimeChunk('single')
}
)
}
}