DLLPlugin 和 DLLReferencePlugin 用某种方法实现了拆分 bundles,同时还大大提升了构建的速度。
1.首先build文件夹添加----webpack.dll.config.js:
var path = require("path");
var webpack = require("webpack");
module.exports = {
// 要打包的模块的数组
entry: {
vendor: ['vue/dist/vue.esm.js','vue-router']
},
output: {
path: path.join(__dirname, '../static/js'), // 打包后文件输出的位置
filename: '[name].dll.js',// vendor.dll.js中暴露出的全局变量名。
library: '[name]_library' // 与webpack.DllPlugin中的`name: '[name]_library',`保持一致。
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, '.', '[name]-manifest.json'),
name: '[name]_library',
context: __dirname
}),
]
};
2.在package.json的scripts里加上:
"dll": "webpack --config build/webpack.dll.config.js",
3.运行npm run dll 在static/js下生成vendor-manifest.json;
4.在build/webpack.base.conf.js里加上:
// 添加DllReferencePlugin插件
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./vendor-manifest.json')
})
],
5.然后在index.html中引入vendor.dll.js:
<div id="app"></div>
<script src="./static/js/vendor.dll.js"></script>
6、删掉 commonsChunkPlugin相关配置,此处建议注释
至此,配置之后的:
可以看到npm run build后的时间大幅度减少,在dist打包体积上也比之前的小。在项目优化中,可以很大程度上加快项目的构建速度和减少项目的打包体积。
补充知识:commonsChunk之所以大,是每次都需要重新打包,而dist打包快,是因为首次打包好依赖的js,后面只需要打包我们改动的js,相当于热部署;
继续优化
1、依赖从package.json读取,而不是手写;
2、带上hash,以免线上缓存问题;
3、带上hash后,自动修改index.html里的引用;
4、命令太长了,最好yarn run一下就好了
webpack.dll.config.js
const path = require('path')
const webpack = require('webpack')
const AssetsPlugin = require('assets-webpack-plugin')
const package = require('./package.json')
let dependencies = Object.keys(package.dependencies) || []
//如果使用了chrome的vue-devtool,那打包的时候把vue也排除掉,因为压缩过的vue是不能使用vue-devtool的
dependencies = dependencies.length > 0 ? dependencies.filter(item => item !== 'vue') : []
module.exports = {
// 要打包的模块的数组
entry: {
vendor: dependencies
},
output: {
path: path.join(__dirname, '../static'), // 打包后文件输出的位置
filename: 'dll.[name]_[hash:6].js',// vendor.dll.js中暴露出的全局变量名。
library: '[name]_[hash:6]' // 与webpack.DllPlugin中的`name: '[name]_library',`保持一致。
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, '.', '[name]-manifest.json'),//. 指当前目录
name: '[name]',
context: __dirname
}),
new AssetsPlugin({
filename: 'bundle-config.json',
path: './'
})
]
}
在build文件夹新建一个dll.js,读一下配置,跑一下webpack,输出点日志
var ora = require('ora')
var chalk = require('chalk')
var webpack = require('webpack')
var webpackConfig = require('./webpack.dll.config')//"dll": "webpack --config build/webpack.dll.config.js"
var spinner = ora('building for dependencies...')
spinner.start()
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
console.log(chalk.cyan(' Build complete.\n'))
})
保存以后,到package.json里添加命令,“dll”: “node build/dll.js”
运行 yarn dll 完成~
参考资料
webpack踩坑记——DllPlugin和DllReferencePlugin
webpack实践——DLLPlugin 和 DLLReferencePlugin的使用