简单来说DllPlugin的作用是预先编译一些模块,而DllReferencePlugin则是把这些预先编译好的模块引用起来。这边需要注意的是DllPlugin必须要在DllReferencePlugin执行前先执行一次,dll这个概念应该也是借鉴了windows程序开发中的dll文件的设计理念。
相对于externals,dllPlugin有如下几点优势:
- dll预编译出来的模块可以作为静态资源链接库可被重复使用,尤其适合多个项目之间的资源共享,如同一个站点pc和手机版等;
- dll资源能有效地解决资源循环依赖的问题,部分依赖库如:react-addons-css-transition-group这种原先从react核心库中抽取的资源包,整个代码只有一句话:
module.exports = require('react/lib/ReactCSSTransitionGroup');
却因为重新指向了react/lib中,这也会导致在通过externals引入的资源只能识别react,寻址解析react/lib则会出现无法被正确索引的情况。
由于externals的配置项需要对每个依赖库进行逐个定制,所以每次增加一个组件都需要手动修改,略微繁琐,而通过dllPlugin则能完全通过配置读取,减少维护的成本;
1、配置dllPlugin对应资源表并编译文件
那么externals该如何使用呢,其实只需要增加一个配置文件:webpack.dll.config.js:
const webpack = require('webpack');
const path = require('path');
const isDebug = process.env.NODE_ENV === 'development';
const outputPath = isDebug ? path.join(__dirname, '../common/debug') : path.join(__dirname, '../common/dist');
const fileName = '[name].js';
// 资源依赖包,提前编译
const lib = [
'react',
'react-dom',
'react-router',
'history',
'react-addons-pure-render-mixin',
'react-addons-css-transition-group',
'redux',
'react-redux',
'react-router-redux',
'redux-actions',
'redux-thunk',
'immutable',
'whatwg-fetch',
'byted-people-react-select',
'byted-people-reqwest'
];
const plugin = [
new webpack.DllPlugin({
/**
* path
* 定义 manifest 文件生成的位置
* [name]的部分由entry的名字替换
*/
path: path.join(outputPath, 'manifest.json'),
/**
* name
* dll bundle 输出到那个全局变量上
* 和 output.library 一样即可。
*/
name: '[name]',
context: __dirname
}),
new webpack.optimize.OccurenceOrderPlugin()
];
if (!isDebug) {
plugin.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.UglifyJsPlugin({
mangle: {
except: ['$', 'exports', 'require']
},
compress: { warnings: false },
output: { comments: false }
})
)
}
module.exports = {
devtool: '#source-map',
entry: {
lib: lib
},
output: {
path: outputPath,
filename: fileName,
/**
* output.library
* 将会定义为 window.${output.library}
* 在这次的例子中,将会定义为`window.vendor_library`
*/
library: '[name]',
libraryTarget: 'umd',
umdNamedDefine: true
},
plugins: plugin
};
内容版权声明:除非注明,否则皆为本站原创文章。
