模块化打包工具webpack以其“黑魔法”构建的方法深受前端er喜爱,但面对慢如龟毛的编译速度,怎么能忍。本文旨在通过介绍DllPlugin与DllReferencePlugin的使用方法,加速webpack的编译过程。同时,生成的依赖库也能解决缓存问题,为页面又加快几秒(逃
-
DllPlugin
先来看官方介绍
This plugin is used in a separate webpack config exclusively to create a dll-only-bundle. It creates a manifest.json
file, which is used by the DllReferencePlugin
to map dependencies.
总结就是为了分散 bundle 包,加快编译过程而生的。通过创建一个名为mainfest.json
的依赖文件,指明依赖项目,为后面构建的bundle包作导引。为此,我们创建一个名为webpack.config.dll.js
的配置文件:
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const CleanWebpackPlugin = require('clean-webpack-plugin')
process.noDeprecation = true
// 入口
var entry = {
// 把有需要打包的常用库封装,如babel-polyfill,jquery等
vendor: ['babel-polyfill', 'vue/dist/vue.runtime.min', 'jquery/dist/jquery.slim.min']
}
var config = {
entry: entry,
output: {
path: path.resolve(__dirname, '../dist/static/js'),
filename: '[name].js',
library: '[name]_library'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
}
]
},
plugins: [
new CleanWebpackPlugin(['dist'], {
root: path.resolve(__dirname, '..')
}),
// 划重点!!
new webpack.DllPlugin({
// 指定路径
path: path.join(__dirname, '../dist', '[name]-manifest.json'),
// 指定依赖库的名称
name: '[name]_library'
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
output: false,
compress: {
unused: true,
dead_code: true,
pure_getters: true,
warnings: false,
screw_ie8: true,
conditionals: true,
comparisons: true,
sequences: true,
evaluate: true,
join_vars: true,
if_return: true
},
comments: false,
minimize: true
})
]
}
module.exports = config
执行webpack --config webpack.config.dll.js
得到打包后的文件
之后,在webpack生产配置文件中添加
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
// webpack plugins
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
var config = {
..
entry
...
output
...
rules
...
plugins: [
// 划重点
new webpack.DllReferencePlugin({
context: path.resolve(__dirname, '..'),
manifest: require('../dist/vendor-manifest.json')
}),
...
htmlwebpacks
...
// 在htmlwebpack后插入一个AddAssetHtmlPlugin插件,用于将vendor插入打包后的页面
new AddAssetHtmlPlugin({ filepath: require.resolve('../dist/static/js/vendor.js'), includeSourcemap: false })
]
}
module.exports = config
至此,搞定!!
END