详解Vue打包优化之code spliting

2020-06-14 05:57:41易采站长站整理

再重新打包,可以看到vue相关的代码已经没有了,目前也只有used-twice-app.js比较大了,app.js缩小了近200kb。

但是新问题又来了,codemirror很大,而used-twice又是首屏需要的,这个打包在首屏肯定不是很好,这里我们要将system和dbmanage页面的codemirror组件改为异步加载,单独打包,修改如下:


// import MCode from "../component/MCode.vue"; //注释掉

components: {
MDialog,
MCode: () => import(/* webpackChunkName: "MCode" */'../component/MCode.vue')
},

重新打包下,可以看到 codemirror被抽离了,首屏代码进一步得到了减少,used-twice-app.js代码缩小了近150k。

做了上面这么多的优化之后,业务测的js基本都被拆到了50kb一下(忽略map文件),算是优化成功了。

总结

可能会有朋友会问,单独分拆vue和vuetify会导致请求数增加,这里我想补充下,我们的业务现在已经切换成http2了,由于多路复用,并且加上浏览器缓存,我们分拆出的请求数其实也算是控制在合理的范畴内。

这里最后贴一下优化后的webpack配置,大家一起交流学习下哈。


const path = require('path')
const webpack = require('webpack')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const generateHtml = new HtmlWebpackPlugin({
title: '逍遥系统',
template: './src/index.html',
minify: {
removeComments: true
}
})

module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].[hash].js',
chunkFilename:'[id].[name].[chunkhash].js'
},
resolve: {
extensions: ['.js', '.vue'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'public': path.resolve(__dirname, './public')
}
},
externals: {
'vue':'Vue',
"vuetify":"Vuetify"
},
module: {
rules: [
{
test: /.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
objectAssign: 'Object.assign'
}
},
{
test: /.css$/,