前言
开发小哥哥说,现在启动好慢呀;测试小姐姐也说,打包太慢了,要一分半呢。
分析
使用webpack-bundle-analyzer分析打包文件
- 安装一下webpack-bundle-analyzer
yarn add webpack-bundle-analyzer –save-dev
- 在 vue.config.conf 上配置一下
chainWebpack(config) {
config
.plugin('webpack-bundle-analyzer')
.use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
.end()
···
}
- 运行一下 yarn dev
由图可知echarts和element-ui比较较大,故先着重优化这两项。
echarts和element-ui的优化,一般着重于按需加载
按需加载
echarts
- 新建一个echarts.js,用于取代 “ import * as echarts from 'echarts';”
// @/src/views/statistic/utils/echart.js
import * as echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/bar'
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/grid'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/title'
import 'echarts/lib/component/tooltip'
export default echarts
- 再来看图
由原来的3.5M优化成了1.5M左右。
PS:也可以用 babel-plugin-equire 来优化,这是一个专门用着echarts按需加载的包
element-ui
主要使用 babel-plugin-component 来按需加载,
- 首先安装 babel-plugin-component
yarn add babel-plugin-component -D
- 在babel.config.js中配置
module.exports = {
plugins: [
[
"component",
{
libraryName: "element-ui",
styleLibraryName: "theme-chalk"
}
]
],
...
}
- 再来看图
element-ui也明显减少了。
我们目前的打包主要是面向构建过程的。
来让我们面向打包过程看看,运行一下 yarn build:prod
看图
目前左上角的chunk包有2M,太大了,我们可以将它拆分一下,将echarts拆出来
- 在vue.config.js上面修改
chainWebpack(config) {
config
.when(process.env.NODE_ENV !== 'development',
config => {
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
},
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
},
...
}
})
}
)
}
- 然后,将routes优化一下,使用 webpackChunkName 将每个页面都打包成一个包
component: () => import(/* webpackChunkName: "userList" */'@/views/user/userList'),
- 好了,我们再看图
目前,我们的打包时间就缩短到了一分钟以内了。
扩展
echarts的按需加载插件:babel-plugin-equire
webpack雪碧图插件:webpack-spritesmith
CSS样式抽离:mini-css-extract-plugin
svg-sprite-loader - npm