webpack的DllPlugin、DllReferencePlugin插件使用,提升打包速度之旅
webpack.dll.js
'use strict'
const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'production',
entry: {
vue: ['vue'],
vueRouter: ['vue-router']
},
output: {
filename: '[name]_[hash].dll.js',
path: path.resolve(process.cwd(), 'dll'),
library: '[name]'
},
plugins: [
new CleanWebpackPlugin(),
new webpack.DllPlugin({
name: '[name]',
path: path.resolve(process.cwd(), 'dll/[name]-manifest.json')
})
]
}
这里如果简单的使用 webpack.DllReferencePlugin ,得每次 npm run dll 后必须复制 dll 文件至 build 目录,并在 index.js 模块文件中引入,势必是有点麻烦。
new webpack.DllReferencePlugin({
manifest: path.resolve(process.cwd(), 'dll/vue-manifest.json'),
}),
new webpack.DllReferencePlugin({
manifest: path.resolve(process.cwd(), 'dll/vueRouter-manifest.json'),
})
那有没有更好的方法,答案是有的,下面我们来一起完成
- 复制 dll 文件至 build 目录
- 批量追加 webpack.DllReferencePlugin
- 添加 dll.js 至模块index.html
所需要依赖模块
npm i -D copy-webpack-plugin
npm i -D add-asset-html-webpack-plugin
npm i -D glob-all
const glob = require('glob-all');
const OtherPlugins = [];
const DllFiles = glob.sync([path.join('dll/**.dll.js')]);
DllFiles.forEach(file => {
OtherPlugins.push(
new AddAssetHtmlWebpackPlugin({
filepath: path.resolve(process.cwd(), file),
publicPath: 'dll'
})
)
})
const ManifestFiles = glob.sync([path.join('dll/**.json')]);
ManifestFiles.forEach(file => {
OtherPlugins.push(
new webpack.DllReferencePlugin({
manifest: path.resolve(process.cwd(), file),
})
)
})
module.exports = {
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './public/index.html',
filename: 'index.html'
}),
new CopyPlugin({
patterns: [
{
from: path.resolve(process.cwd(), 'dll'),
to: path.resolve(process.cwd(), 'dist/dll')
}
]
})
].concat(OtherPlugins)
}
这样是不是很简洁就实现了,是不是比手动添加更新方便。
当然还有很多其它方式可以实现,笔者这只是抛砖引玉。
比如:
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.jade',
inject: {
head: ['chunks2'],
body: ['chunks1', 'chunks3', 'vendor']
},
chunks: ['chunks1', 'chunks2', 'chunks3', 'vendor']
})
HtmlWebpackPlugin 模板是支持 ejs 语法,还可以在模板中使用 ejs for 循环实现。