公共模块按需打包
在项目进行中,会应用很多公共的模块,其实这些模块是不会变动的,在后期项目优化的时候,用到了 webpack
下的 DLLPlugin
和 DLLReferencePlugin
,记录一下。
配置 dll.config.js
const webpack = require('webpack');
const path = require('path')
// 需要提取的公共模块
const vendors = [
'vue',
'vue-router',
'lodash',
'vuex',
'fastclick',
'axios'
];
module.exports = {
output: {
path: path.resolve(__dirname, '../static/js'), // 打爆出来的文件存放路径
filename: '[name].dll.js', // 文件名
library: '[name]_library' //
},
entry: {
vendor: vendors, // 公共的模块
},
plugins: [
new webpack.DllPlugin({
// 输出路径
path: path.join(__dirname, '.', '[name]-manifest.json'),
// 与上面的 output.library 对应
name: '[name]_library',
// 上下文环境
context: __dirname
}),
// 压缩
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: false
}),
],
};
执行公共模块压缩
webpack --config dll.config.js
执行后会生成一个 js
文件和一个 json
文件,json
文件用于 webpack
打包, js
文件直接在 index
上引用即可。
配置 webpack
module.exports = {
entry: {
···
},
output: {
···
},
resolve: {
···
},
module: {
···
},
plugins: [
new webpack.DllReferencePlugin({
// 与 dll.config.js 中的 context 一致
context: __dirname,
// 生成的 json 文件的地址
manifest: require('./vendor-manifest.json')
})
]
}
在配置项中加入 DllReferencePlugin
即可。