Webpack 5 引入了持久化缓存功能,可以显著提高后续构建的速度。
// webpack.config.js
module.exports = {
// 其他配置
cache: {
type: 'filesystem', // 使用文件系统缓存
},
};
将应用程序分割为多个入口点,可以更好地利用缓存并减少每次构建的时间。
// webpack.config.js
module.exports = {
entry: {
app: './src/app.js',
admin: './src/admin.js',
},
// 其他配置
};
babel-loader
的缓存在使用 Babel 转译代码时,可以启用缓存来加快构建速度。
// webpack.config.js
module.exports = {
// 其他配置
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true, // 启用缓存
},
},
exclude: /node_modules/,
},
],
},
};
thread-loader
启用多进程thread-loader
可以为 Babel 或其他繁重的 loader 启用多进程处理,从而加快构建速度。
// webpack.config.js
module.exports = {
// 其他配置
module: {
rules: [
{
test: /\.js$/,
use: [
'thread-loader',
'babel-loader',
],
exclude: /node_modules/,
},
],
},
};
resolve
配置减少模块解析的工作量,例如缩小 resolve.modules
和 resolve.extensions
的范围。
// webpack.config.js
module.exports = {
// 其他配置
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
extensions: ['.js', '.json', '.jsx', '.css'],
},
};
DllPlugin
使用 DllPlugin
将第三方库单独打包,可以减少每次构建时的工作量。
// webpack.dll.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
vendor: ['react', 'react-dom'],
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].dll.js',
library: '[name]_dll',
},
plugins: [
new webpack.DllPlugin({
name: '[name]_dll',
path: path.resolve(__dirname, 'dist', '[name].json'),
}),
],
};
在生产环境中,可以使用 TerserWebpackPlugin 来压缩代码,加快加载速度。
// webpack.config.js
const TerserWebpackPlugin = require('terser-webpack-plugin');
module.exports = {
// 其他配置
optimization: {
minimize: true,
minimizer: [new TerserWebpackPlugin()],
},
};
exclude
和 include
规则在 loader 中使用 exclude
和 include
选项来减少处理的文件数量。
// webpack.config.js
module.exports = {
// 其他配置
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'), // 只处理 src 目录下的文件
exclude: /node_modules/, // 排除 node_modules 目录
use: 'babel-loader',
},
],
},
};
webpack-parallel-uglify-plugin
这个插件可以使用多进程并行运行 UglifyJS,从而加快压缩速度。
// webpack.config.js
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
module.exports = {
// 其他配置
plugins: [
new ParallelUglifyPlugin({
uglifyJS: {
output: {
comments: false,
},
compress: {
warnings: false,
},
},
}),
],
};
IgnorePlugin
忽略大型库的本地化文件例如,忽略 moment
的本地化文件。
// webpack.config.js
const webpack = require('webpack');
module.exports = {
// 其他配置
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
};
将 CSS 提取到单独的文件中,减少 JavaScript 的大小,加快加载速度。
// webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
// 其他配置
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
};