vue-cli3 DllPlugin 提取公用库的方法
vue开发过程中,保存一次就会编译一次,如果能够减少编译的时间,哪怕是一丁点,也能节省不少时间。开发过程中个人编写的源文件才会频繁变动,而一些库文件我们一般是不会去改动的。如果能把这些库文件提取出来,就能减少打包体积,加快编译速度。本文主要讲述在vue-cli3中利用DllPlugin来进行预编译。
1、安装相关插件
yarnaddwebpack-cli@^3.2.3add-asset-html-webpack-plugin@^3.1.3clean-webpack-plugin@^1.0.1--dev
2、编写配置文件
在项目根目录下新建webpack.dll.conf.js,输入以下内容。
constpath=require('path')
constwebpack=require('webpack')
constCleanWebpackPlugin=require('clean-webpack-plugin')
//dll文件存放的目录
constdllPath='public/vendor'
module.exports={
entry:{
//需要提取的库文件
vendor:['vue','vue-router','vuex','axios','element-ui']
},
output:{
path:path.join(__dirname,dllPath),
filename:'[name].dll.js',
//vendor.dll.js中暴露出的全局变量名
//保持与webpack.DllPlugin中名称一致
library:'[name]_[hash]'
},
plugins:[
//清除之前的dll文件
newCleanWebpackPlugin(['*.*'],{
root:path.join(__dirname,dllPath)
}),
//设置环境变量
newwebpack.DefinePlugin({
'process.env':{
NODE_ENV:'production'
}
}),
//manifest.json描述动态链接库包含了哪些内容
newwebpack.DllPlugin({
path:path.join(__dirname,dllPath,'[name]-manifest.json'),
//保持与output.library中名称一致
name:'[name]_[hash]',
context:process.cwd()
})
]
}
3、生成dll
在package.json中加入如下命令
"scripts":{
...
"dll":"webpack-p--progress--config./webpack.dll.conf.js"
},
控制台运行
yarnrundll
4、忽略已编译文件
为了节约编译的时间,这时间我们需要告诉webpack公共库文件已经编译好了,减少webpack对公共库的编译时间。在项目根目录下找到vue.config.js(没有则新建),配置如下:
constwebpack=require('webpack')
module.exports={
...
configureWebpack:{
plugins:[
newwebpack.DllReferencePlugin({
context:process.cwd(),
manifest:require('./public/vendor/vendor-manifest.json')
})
]
}
}
5、index.html中加载生成的dll文件
经过上面的配置,公共库提取出来了,编译速度快了,但如果不引用生成的dll文件,网页是不能正常工作的。
打开public/index.html,插入script标签。
...
到此公用库提取完成,但总觉得最后一部手工插入script不太优雅,下面介绍下如何自动引入生成的dll文件。
打开vue.config.js在configureWebpackplugins节点下,配置add-asset-html-webpack-plugin
constpath=require('path')
constwebpack=require('webpack')
constAddAssetHtmlPlugin=require('add-asset-html-webpack-plugin')
module.exports={
...
configureWebpack:{
plugins:[
newwebpack.DllReferencePlugin({
context:process.cwd(),
manifest:require('./public/vendor/vendor-manifest.json')
}),
//将dll注入到生成的html模板中
newAddAssetHtmlPlugin({
//dll文件位置
filepath:path.resolve(__dirname,'./public/vendor/*.js'),
//dll引用路径
publicPath:'./vendor',
//dll最终输出的目录
outputPath:'./vendor'
})
]
}
}
总结
以上所述是小编给大家介绍的vue-cli3DllPlugin提取公用库的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!