1.安装相关的插件
npm install webpack-cli@^3.2.3 add-asset-html-webpack-plugin@^3.1.3 clean-webpack-plugin@^1.0.1 --dev
2.新建配置文件
在项目根目录新建webpack.dll.config.js,并进行相关配置
const path = require('path')
const webpack = require('webpack')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const dllPath = 'public/vendor'
module.export={
entry: {
vendor: ["vue", "vue-router", "vuex"],
},
output: {
path: path.join(__dirname, dllPath),
filename: "[name].dll.js",
library: "[name]_[hash]",
},
plugins: [
new CleanWebpackPlugin(["*.*"], {
root: path.join(__dirname, dllPath),
}),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: "production",
},
}),
new webpack.DllPlugin({
path: path.join(__dirname, dllPath, "[name]-manifest.json"),
// 保持与 output.library 中名称一致
name: "[name]_[hash]",
context: process.cwd(),
}),
],
}
3.设置dll命令
在package.json中加入以下配置
"dll": "webpack -p --progress --config ./webpack.dll.config.js"
终端运行
npm run dll
4.忽略已编译文件
为了节约编译的时间,这时间我们需要告诉 webpack 公共库文件已经编译好了,减少 webpack 对公共库的编译时间。在项目根目录下找到 vue.config.js ( 没有就新建 ),配置如下:
const webpack = require('webpack')
const AddAssetHtmlPlugin = require("add-asset-html-webpack-plugin");
module.exports={
...
configureWebpack:{
plugins:[
...
new webpack.DllReferencePlugin({
context: process.cwd(),
manifest: require("./public/vendor/vendor-manifest.json"),
}),
new AddAssetHtmlPlugin({
filepath: path.resolve(__dirname, "./public/vendor/*.js"),
publicPath: "./vendor",
outputPath: "./vendor",
}),
]
}
PS:配置 add-asset-html-webpack-plugin可以将将 dll 注入到 生成的 html 模板中,无需手动在public/index.html 手动引入 <script src="./vendor/vendor.dll.js"></script>