Webpack 中的 DllPlugin 是一个非常有用的插件,它可以将一些不经常变动的第三方库代码提前打包好,以减少每次构建时的重复打包时间。这样可以提高构建速度,特别是在大型项目中。
安装
首先,我们需要安装 webpack 和 DllPlugin 插件:
npm install webpack webpack-cli webpack-dev-server webpack-dll-plugin --save-dev
配置
在项目根目录下创建一个 webpack.dll.js 配置文件,配置如下:
// www.javascriptcn.com code example
const path = require('path');
const webpack = require('webpack');
const DllPlugin = require('webpack-dll-plugin');
module.exports = {
mode: 'production',
entry: {
vendor: ['react', 'react-dom', 'lodash']
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].dll.js',
library: '[name]'
},
plugins: [
new DllPlugin({
name: '[name]',
path: path.resolve(__dirname, 'dist/[name].json')
})
]
};使用
在项目根目录下创建一个 webpack.config.js 文件,配置如下:
// www.javascriptcn.com code example
const path = require('path');
const webpack = require('webpack');
const DllReferencePlugin = webpack.DllReferencePlugin;
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
plugins: [
new DllReferencePlugin({
manifest: require('./dist/vendor.json')
})
]
};在 index.js 文件中引入第三方库:
import React from 'react'; import ReactDOM from 'react-dom'; import _ from 'lodash'; // Your code here
最后,运行 webpack 构建命令:
npx webpack --config webpack.dll.js npx webpack --config webpack.config.js
这样就可以看到第三方库被提前打包好,加快了构建速度。