在用webpack打包的时候通常来说,node_modules里的npm包会打包成一个js文件(chunk-vendor.js),业务代码会打包成一个js文件(main.js)。
- main.js里的文件大小优化可以启用懒加载:路由懒加载,模块懒加载
- chunk-vendor.js文件的的优化可以用dll方式就将核心的npm分离出来几个js文件引入
webpack.dll.config.js文件的配置
const { resolve } = require('path');
const webpack = require('webpack')
const CleanWebpackPlugin = require('clean-webpack-plugin')
module.exports={
entry:{
vue:['vue','vue-router','axios'],
vendor:['xxx','xxx','xxx']
},
output:{
filename:'[name].dll.js',
path:resolve(__dirname,'dll'),
library:'[name]_dll_[hash]'
},
plugins:[
new webpack.DllPlugin({
name:'[name]_dll_[hash]',
path:resolve(__dirname,'dll/[name].manifest.json')
}),
new CleanWebpackPlugin()
],
mode:'production'
}
vue.config.js的配置
const AddAssetHtmlPlugin = require("add-asset-html-webpack-plugin")
new webpack.DllReferencePlugin(
{manifest:resolve('dll/vue.manifest.json')}
),
new webpack.DllReferencePlugin(
{manifest:resolve('dll/vendor.manifest.json')}
)
new AddAssetHtmlPlugin([
{ filepath: require.resolve('./dll/vue.dll.js') },
{ filepath: require.resolve('./dll/vendor.dll.js') },
])
其中插件版本如果不一样可能会出现打包报错的问题
- 查看npm包版本的方式:npm ls compression-webpack-plugin
- 我打包的compression-webpack-plugin version 1.1.12
- add-asset-html-webpack-plugin version 3.2.0
- webpack版本:4.46.0
- webpack-cli版本 3.0多
gzip压缩
const CompressionPlugin = require('compression-webpack-plugin');
new CompressionPlugin({
test: /\.js$|\.css/,
threshold:10240,
deleteOriginalAssets:false
})
nginx配置:
server:{
gzip on;
gzip_types text/plain application/javascript text/css text/javascript;
}
加载时性能指标