webpack使用DllPlugin
什么是webpack dll
DLL是一种提供公共的可调用的函数或数据的动态链接库,webpack中以插件的形式进行支持,webpack内置的dllPlugin支持将公共的代码从bundle中分离出来作为一个独立的dll,并配合DllReferencePlugin插件在bundle中映射到对应的依赖上,这个分离出来的dll在一次编译后不在参与业务代码编译的过程能极大的提升项目编译效率
构建DLL文件
webpack的dll文件构建需要独立打包需要添加一份新的dll打包配置如文件webpack.config.dll.js,并在entry中申明dll文件名称及包含的包或文件,并引入DllPlugin插件即可,如需要编译ts/tsx之类的代码块添加对应的loader即可
// webpack.config.dll.js
module.exports = {
mode: 'production',
entry: {
// 需要提取的库
vendor: ['react', 'react-dom']
},
// 输出配置
output: {
path: path.resolve(__dirname, 'dist/dll'),
filename: '[name].js',
library: "[name]_[fullhash]"
},
// 插件
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, "dist/dll", "[name]-manifest.json"),
name: "[name]_[fullhash]"
})
]
}
使用DLL
在编译阶段使用
只需要引入DllReferencePlugin插件并指定manifest文件地址即可
{
mode: 'production',
entry: {
bundle: './src/index.tsx'
},
devtool: "source-map",
// 输出配置
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
// 插件
plugins: [
new webpack.DllReferencePlugin({
manifest: require('./dist/dll/vendor-manifest.json')
}),
]
}
在开发阶段使用
需要注意开发阶段需要能够访问到已编译的dll文件,这里采用的是将dll文件夹以静态文件的方式提供
{
mode: 'development',
entry: {
bundle: './src/index.tsx',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
devServer: {
static: [
{
directory: path.join(__dirname, 'public'),
serveIndex: true
},
{
directory: path.join(__dirname, 'dist/dll'),
serveIndex: true
}
],
},
plugins: [
new webpack.DllReferencePlugin({
manifest: require('./dist/dll/vendor-manifest.json')
}),
]
}

浙公网安备 33010602011771号