DLL(Dynamic Link Library)动态链接库在 webpack 中用来将可共享且不常改变的代码抽取成公共的库。
react和 react-dom在 react 项目中是必备的两个库,把它们抽取出来单独打个包。
首先进行安装 npm install react react-dom --save
在 src 目录下新建 index.jsx 文件,编写 react 代码
import React, { Component } from 'react';
export default class App extends Component {
state = {
message: 'hello react ',
};
render() {
return <div>{this.state.message}</div>;
}
}
在一层级的 index.js 中引入 react 组件,并安装 axios后使用它来发送一个请求
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.jsx';
import axios from 'axios';
ReactDOM.render(<App />, document.getElementById('container'));
axios.get('https://httpbin.org/get').then((res) => {
console.log('res', res);
});
react 代码需要通过 babel 进行处理,可以参考 这篇文章,在没有使用 DLL 的时候,第三方库 react react-dom和 axios都被打包到了 702.js 文件中。

如果需要对某些资源单独打包,就可以使用到 DLL,新建 webpack.dll.js文件,自定义编译规则,通过 DllPlugin生成 manifest.json文件,其中包含依赖的映射关系。
const { DllPlugin } = require('webpack');
const path = require('path');
module.exports = {
entry: {
react: ['react', 'react-dom'],
},
output: {
filename: './[name].js',
path: path.resolve(process.cwd(), './dll'),
library: '[name]',
},
plugins: [
new DllPlugin({
name: '[name]',
path: path.resolve(__dirname, './dll/manifest.json'),
}),
],
};
执行 npx webapck --config ./webpack.dll.js后,生成三个文件,mainfest.json,react.js和一个注释文件(可通过TerserPlugin去除)

如果此时直接编译 webpack.config.js文件的话,react和 react-dom还是会被作为第三方库和 axios编译到一起。
虽然已经通过 DLL将 react和 react-dom自行打包了,但是没有告诉 webpack.config.js不需要再把这两者打包到公共的库中。这时候请出 DllReferencePlugin来处理。
const { DllReferencePlugin } = require('webpack');
module.exports = {
// 其它配置省略
plugins: [
new DllReferencePlugin({
manifest: path.resolve(process.cwd(), './dll/manifest.json'),
context: path.resolve(process.cwd(), './'),
}),
],
};
此时第三方库的 js 文件里已经没有了 react和 react-dom,文件名由 702.js 变成了 559.js 是因为内容发生了变化。

运行编译后的 index.html 文件,发现报错 react is not defined,也没有在页面中显示 hello react的代码。

这是因为第三库打包的 js 文件中排除了 react 和 react-dom,自行打包的 react.js又没有被引入到 html 文件中,所以执行的时候就找不到文件了。
安装插件 add-asset-html-webpack-plugin,通过它来引入文件到 html 中
const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin');
module.exports = {
// 其它配置省略
plugins: [
new AddAssetHtmlWebpackPlugin({
filepath: path.resolve(process.cwd(), './dll/react.js'),
outputPath: './auto',
}),
],
};
这样通过 DLL编译的 react.js文件就被引入到 html 文件中,页面也能正常显示

使用 DLL可以自定义打包的内容,分为以下三个步骤。
webpack.dll.js中使用 DllPlugin生成 mainfest.json 和 js 文件webpack.config.js中使用 DllReferencePlugin去 mainfest.json 文件中找到映射关系,排除不需要打包的库webpack.config.js中通过 add-asset-html-webpack-plugin在 html 文件引入资源以上是关于使用 DLL打包的总结, 更多有关 webpack的内容可以参考我其它的博文,持续更新中~