DLL(Dynamic Link Library)动态链接库在 webpack 中用来将可共享且不常扭转的代码抽取成公共的库。

没有应用 DLL

reactreact-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-domaxios 都被打包到了 702.js 文件中。

打包DLL库

如果须要对某些资源独自打包,就能够应用到 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.jsonreact.js 和一个正文文件(可通过TerserPlugin去除)

如果此时间接编译 webpack.config.js 文件的话,reactreact-dom还是会被作为第三方库和 axios 编译到一起。

引入DLL库

尽管曾经通过 DLLreactreact-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 文件里曾经没有了 reactreact-dom,文件名由 702.js 变成了 559.js 是因为内容产生了变动。

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

将文件增加到 html 中

这是因为第三库打包的 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 的内容能够参考我其它的博文,继续更新中~