🌞

三行代码提速 webpack 构建

找出关键问题分析项目发现主要的耗时在 chunk asset optionzation uglifyjsPlugin 而且经常会出现内存溢出(node 10)92% chunk asset optim

文链接在语雀:https://www.yuque.com/wumingshi/rkh1qq/

找出关键问题

分析项目发现主要的耗时在 chunk asset optionzation uglifyjsPlugin 而且经常会出现内存溢出(node 10)

92% chunk asset optimization UglifyJSPlugin
<--- Last few GCs --->

[72397:0x110008000]   373919 ms: Scavenge 1268.5 (1422.2) -> 1267.7 (1422.7) MB, 3.8 / 0.0 ms  (average mu = 0.344, current mu = 0.396) allocation failure 
[72397:0x110008000]   373925 ms: Scavenge 1268.6 (1422.7) -> 1267.8 (1423.2) MB, 3.9 / 0.0 ms  (average mu = 0.344, current mu = 0.396) allocation failure 
[72397:0x110008000]   373930 ms: Scavenge 1268.7 (1423.2) -> 1267.9 (1423.7) MB, 3.8 / 0.0 ms  (average mu = 0.344, current mu = 0.396) allocation failure 


<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x17a4c305be3d]
    1: StubFrame [pc: 0x17a4c3053d68]
Security context: 0x0860e0b9e6e9 <JSObject>
    2: split [0x860e0b906c9](this=0x08605339a339 <String[6]: column>,0x08605339a381 <JSRegExp <String[5]: \r?\n>>)
    3: print(aka print) [0x860feb524a9] [0x0860db2826f1 <undefined>:~5771] [pc=0x17a4c7a10895](this=0x0860db2826f1 <undefined>,str=0x08605339a339 <String[6]: column>)
    4: print_name [0x860feb41599] [0x086...

直接打破

step 1: 替换js压缩插件,替换 terser-webpack-plugin 或者 uglifyjs-webpack-plugin

const { ESBuildMinifyPlugin } = require('esbuild-loader');
optimization.minimizer = [new ESBuildMinifyPlugin({
    target: 'es2015',
})]

step2: 替换 css 压缩

const { ESBuildMinifyPlugin } = require('esbuild-loader');
optimization.minimizer = [new ESBuildMinifyPlugin({
    target: 'es2015',
+   css: true,
})]

去掉 optimize-css-assets-webpack-plugin
- optimization.minimizer.push(
-      new MinifyCssPlugin()
- );

替换后的总体构建时长对比

替换前

General output time took 5 mins, 17.82 secs  

替换后

General output time took 1 min, 20.3 secs

最后

webpack4以后dll对构建的影响几乎可以忽略不计了,二次构建也可以考虑使用hardsourceplugin,但这个对线上构建影响很小(线上构建一般都会初始化新的容器)

babel一系列plugin无法平滑过度到esbuild,挺遗憾的无法享受到构建js的便利,尝试使用 swc 进行babel替换,初次试验也宣告失败。

updatedupdated2023-10-312023-10-31