最近看了一个性能优化的小册,包含webpack配置DllPlugin,用公司项目跟着去配置下才发现配置起来格外吃力,因为以前确实了解的少了。为了下次配置能节省时间,自己做一个记录,也还是要抓紧补上webpack知识吧。
1、创建名为dll.js的文件,配置如下:
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: {
//一些依赖库,也不知道配的对不对,没有标准答案
vendor: ['echarts', 'vue-router', 'vue-quill-editor', 'element-ui', 'vue/dist/vue.esm.js']
},
output: {
path: path.join(__dirname, 'target'),
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.DllPlugin({
// DllPlugin的name属性需要和libary保持一致
name: '[name]_[hash]',
//指定当前目录
path: path.join(__dirname, '.', '[name]-manifest.json'),
// context需要和webpack.config.js保持一致
context: __dirname
})
]
}
2、创建好后运行文件,需下载webpack-cli
npm install webpack-cli
//查看webpack版本号 webpack -v是无用的
npm info webpack
//直接webpack dll.js不行,不知为何
//只能在package.json文件的scripts配置"dll": "webpack --config ./dll.js"
//运行文件
npm run dll
会打包生成vendor-manifest.json文件
3、vue.config.js配置
const webpack = require('webpack')
module.exports = {
//二者选其一
chainWebpack: config => {
config.plugin('dll-reference-plugin')
.use(webpack.DllReferencePlugin)
.tap(options => {
options[0] = {
context: __dirname,
// manifest就是我们第2步中打包出来的json文件
manifest: require(path.join(__dirname, `./vendor-manifest.json`))
}
return options
})
},
configureWebpack: config => {
config.plugins.push(new webpack.DllReferencePlugin({
context: __dirname,
// manifest就是我们第2步中打包出来的json文件
manifest: require('./vendor-manifest.json')
}))
}
}
如果是在webpack.config.js配置
const path = require('path');
const webpack = require('webpack')
module.exports = {
// dll相关配置
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
// manifest就是我们第2步中打包出来的json文件
manifest: require('./vendor-manifest.json'),
})
]
}
配置完成了,打包体积变化许多,但打包时间没找到办法显示,只能作罢。
花了许多时间完成的东西还是值得记录一下,想继续优化也可以在此基础上改进。