详解webpack提取第三方库的正确姿势
我们在用webpack打包是时候,常常想单独提取第三方库,把它作为稳定版本的文件,利用浏览缓存减少请求次数。常用的提取第三方库的方法有两种
- CommonsChunkPlugin
- DLLPlugin
区别:第一种每次打包,都要把第三方库也运行打包一次,第二种方法每次打包只打包项目文件,我们只要引用第一次打包好的第三方压缩文件就行了
CommonsChunkPlugin方法简介
我们拿vue举例
constvue=require('vue')
{
entry:{
//bundle是我们要打包的项目文件的导出名字,app是入口js文件
bundle:'app',
//vendor就是我们要打包的第三方库最终生成的文件名,数组里是要打包哪些第三方库,如果不是在node——modules里面,可以填写库的具体地址
vendor:['vue']
},
output:{
path:__dirname+'/bulid/',
//文件名称
filename:'[name].js'
},
plugins:{
//这里实例化webpack.optimize.CommonsChunkPlugin构造函数
//打包之后就生成vendor.js文件
newwebpack.optimize.CommonsChunkPlugin('vendor','vendor.js')
}
}
然后打包生成的文件引入到html文件里面
DLLPlugin方法简介
首先准备两个文件
- webpack.config.js
- webpack.dll.config.js
webpack.dll.config.js文件配置如下
constwebpack=require('webpack')
constlibrary='[name]_lib'
constpath=require('path')
module.exports={
entry:{
vendors:['vue','vuex']
},
output:{
filename:'[name].dll.js',
path:'dist/',
library
},
plugins:[
newwebpack.DllPlugin({
path:path.join(__dirname,'dist/[name]-manifest.json'),
//Thismustmatchtheoutput.libraryoptionabove
name:library
}),
],
}
然后webpack.config.js文件配置如下
constwebpack=require('webpack')
module.exports={
entry:{
app:'./src/index'
},
output:{
filename:'app.bundle.js',
path:'dist/',
},
plugins:[
newwebpack.DllReferencePlugin({
context:__dirname,
manifest:require('./dist/vendors-manifest.json')
})
]
}
然后运行
$webpack--configwebpack.dll.config.js $webpack--configwebpack.config.js
html引用方式
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。