描述
在vue项目打包后,发现到生产环境加载特别慢,首页白屏时间太久,控制台查看请求时间发现有一个1-2m的chunk-vendors
开头的js文件加载特别慢,用了我整整十几秒钟。然后我用webpack-bundle-analyzer
插件分析了一下打包后的文件,果然是它。
解决
最简单的额办法就是拆分js文件 以vue-cli3为例,配置文件增加相关配置
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV === 'production') {
// 开启分离js
config.optimization = {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 20000,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name (module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`
}
}
}
}
};
}
}
}
重新打包后再次分析,效果很明显:
但是要想有更好的性能体验不单单就这么多。
还要 CDN 路由懒加载 配合Nginx进行代码压缩 等等
END