1. 首先將需要打包的文件打包為dll
需要一個打包配置 webpack.dll.js
const webpack = require('webpack') const path = require('path') module.exports = { entry: { react: ['react', 'react-dom'] }, output: { library: 'react', // 以一個庫的形式導出 filename: '[name].dll.js' }, plugins: [ new webpack.DllPlugin({ name: 'react', path: path.resolve(__dirname, 'dist/manifest.json') }) ] }
生成一個 react.dll.js打包文件和一個結構文件manifest.json,manifest.json用於讀取打包前文件后打包后文件的對應關系,
可能會有多組文件需要打包。
打包命令
"script" : { "dll": "webpack --config webpack.dll.js --mode=development" }
2. 項目中引入打包的結構文件,頁面中引入打包文件
plugins: [ new webpack.DllReferencePlugin({ manifest: path.resolve(__dirname, 'dist/manifest.json') }), new AddAssetHtmlPlugin({ filepath: path.resolve(__dirname, 'dist/react.dll.js') }) ]
3. 使用AtuoDllPlugin快速完成dll打包
上面的步驟中的打包配置略顯繁瑣,可以使用autodll-webpack-plugin代替上面的配置
new AutoDllPlugin({ inject: true, // will inject the DLL bundle to index.html debug: true, filename: '[name]_[hash].js', context: path.join(__dirname, '..'), path: './dll', entry: { vendor: [ 'react','react-dom' ] } })