為什么需要優化
相信使用過webpack的童鞋應該有體會到,在文件相對較龐大時,webpack的構建速度是非常慢的,那這樣的話對我們的開發人員來說體驗非常不好。
優化的方式
性能優化方式有很多,這里來介紹一下dll,dll是一種最簡單粗暴並且極其有效的優化方式,且我的公司項目也是用的這種方式
如何使用dll優化
在用 Webpack 打包的時候,對於一些不經常更新的第三方庫,比如 vue,lodash,我們希望能和自己的代碼分離開。
對於這種方式優化的項目,一般有兩個配置文件,分別是:
1.webpack.config.js
2.webpack.dll.config.js
下面以我的公司項目的webpack.dll.config.js為例:
const path = require('path')
const webpack = require('webpack');
const merge = require('webpack-merge')
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const utils = require('./utils')
const config = require('./config')
const dllConfig = {
context: path.resolve(__dirname, '../'),
output: {
path: path.resolve(__dirname, '..', config.build.assetsSubDirectory),
filename: '[name].js',
library: '[name]'
},
entry: {
lib: [
'lodash/assignIn',
'lodash/isPlainObject',
'lodash/isArray',
'lodash/isString',
'axios',
'moment',
'numeral',
'numeral/locales',
'vue/dist/vue.js',
'vue-router',
'jquery',
'url-join',
// 'element-ui',
// 'element-ui/lib/theme-chalk/index.css',
'reset-css'
],
},
module: {
rules: [{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff",
options: {
name: utils.assetsPath('fonts/[name].[ext]')
}
}, {
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader",
options: {
name: utils.assetsPath('fonts/[name].[ext]')
}
}]
},
plugins: [
new webpack.DllPlugin({
context: __dirname,
path: '.webpack-dll-manifest.json',
name: '[name]',
}),
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
}),
new ExtractTextPlugin('[name].css'),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
}),
]
}
module.exports = merge(dllConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
}
})
在執行了webpack --config webpack.dll.config.js命令之后,在dll目錄下會生成三個文件:webpack-dll-manifest.json、report.html、lib.js
此命令將axios,lodash/assignIn,vue-router等合並打包為一個名為 lib.js 的靜態資源包,同時生成一個 webpack-dll-manifest.json 文件方便對 lib.js 中的模塊進行引用。
webpack-dll-manifest.json給各個模塊賦予 id 以便引用。

在webpack.config.js文件中,添加引用即可
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./dll/manifest.json')
})
]
