2023-05-17
webpack5编译速度优化

使用webpack5 默认的配置,在开发阶段编译速度太慢,优化完成之后,可以从60S的速度提升到1S的速度~

没优化之前

  • 初次启动项目需要将近100S
    初次启动项目 98S

  • 热更新耗时68S 热更新耗时68S

优化之后

  • 初次启动项目仅需要不到30S
    初次启动项目 30S

  • 热更新耗时不到2S 热更新耗时不到2S

1. 处理webpack缓存
官方文档

1
2
3
4
5
6
7
8
9
10
11
// webpack.config.js
module.exports = (env) => {
...,
// 缓存生成的 webpack 模块和 chunk,来改善构建速度。cache 会在开发 模式被设置成 type: 'memory' 而且在 生产 模式 中被禁用。 cache: true 与 cache: { type: 'memory' } 配置作用一致。 传入 false 会禁用缓存 默认 false
cache: env.WEBPACK_BUILD ? false :
{
type: 'filesystem' // 将 cache 类型设置为内存或者文件系统。memory 选项很简单,它告诉 webpack 在内存中存储缓存,不允许额外的配置 默认 memory
},
...

}

2. 处理babel-loader缓存
官方文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 在rules: babel-loader 中,如果 将node_modules 不排除的话,将会有不可计数的modules参与计算,会大大减慢编译速度。
// babel-loader options: 设置缓存之后,可以将loader的执行结果进行缓存,之后的变异将会读取缓存。

// webpack.config.js
module.exports = (env) => {
...,
module: {
rules: [
...,
{
test: /\.js$/,
exclude: {
and: [/node_modules/], // Exclude libraries in node_modules ...
not: [
// Except for a few of them that needs to be transpiled because they use modern syntax
/xiangxin-element/,
],
},
use: [
{
loader: "babel-loader",
options: {
cacheDirectory: !env.WEBPACK_BUILD,// 是否开启babel编译缓存 默认值为 false
cacheCompression: !!env.WEBPACK_BUILD, // 缓存文件是否压缩 默认值为 true 压缩
presets: [
[
"@babel/preset-env",
{
useBuiltIns: "usage",
corejs: {
version: 3,
proposals: true, // 使用尚在“提议”阶段特性的 polyfill
},
targets: "ie 11",
},
],
],
// 下面指的是在生成的文件中,不产生注释
comments: false,
},
},
],
},
...
],
},
...
}

3. 代码压缩在开发过程中,无需压缩代码
官方文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// minimize 开发过程中无需代码压缩

// webpack.config.js
module.exports = (env) => {
...,

optimization: {
...
minimize: !!env.WEBPACK_BUILD,
minimizer: [
// 设置打包不开启多线程
new TerserPlugin( {
parallel: !env.WEBPACK_BUILD,
extractComments: false,
} ),
],
},
...
}
Read More