webpack

如何提升 webpack 的构造性能

1. speed-measure-webpack-plugin

优化你的 webpack 构建速度的第一步是要知道你应该把注意力集中在哪里,在这里推荐一个插件:speed-measure-webpack-plugin,这个插件可以测量你的 webpack 构建速度

install

1
npm install --save-dev speed-measure-webpack-plugin

or

1
yarn add -D speed-measure-webpack-plugin

用法

1
2
3
const webpackConfig = {
plugins: [new MyPlugin(), new MyOtherPlugin()],
};

to

1
2
3
4
5
6
7
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");

const smp = new SpeedMeasurePlugin();

const webpackConfig = smp.wrap({
plugins: [new MyPlugin(), new MyOtherPlugin()],
});

2. 更快的 loader:swc

在 webpack 中耗时最久的当属负责 AST 转换的 loader。我们可以使用速度更快的swc

1
2
3
4
5
6
7
8
9
10
11
12
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
// Use `.swcrc` to configure swc
loader: "swc-loader",
},
},
];
}

如何配置 swc

SWC can be configured with an .swcrc file.

this is Compilation

如果你是使用的 babel,swc 官方网站拥有提供从 babel 迁移到 swc 的指南

3. 持久化缓存:cache

webpack5 内置了关于缓存的插件,可以通过配置来开启,它将ModuleChunkModuleChunk等信息序列化到磁盘中,二次构建避免重复编译计算,编译速度得到很大的提升

1
2
3
4
5
{
cache: {
type: "filesystem";
}
}

当开启了持久化缓存功能,最耗时的 AST 解析将能够从磁盘的缓存中获取,再次编译时无需再次进行解析 AST。