解决 Node.js 打包提示内存溢出-JavaScript heap out of memory

2,142 阅读1分钟

公司 gitlab ci/cd 打包前端项目的时候报错了,一眼就看出报了内存溢出,但是无从下手,只能 Google 一下。

线上打包结果:

image.png

<--- Last few GCs --->

[109:0x7fce91599340]    71875 ms: Mark-sweep (reduce) 2023.8 (2082.8) -> 2023.3 (2083.3) MB, 1051.4 / 0.0 ms  (average mu = 0.207, current mu = 0.008) allocation failure scavenge might not succeed
[109:0x7fce91599340]    73456 ms: Mark-sweep (reduce) 2024.3 (2083.3) -> 2023.9 (2084.1) MB, 1578.2 / 0.0 ms  (average mu = 0.094, current mu = 0.002) allocation failure scavenge might not succeed

<--- JS stacktrace --->

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
error Command failed with signal "SIGABRT".
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
ERROR: Job failed: exit code 1

本地打包没有问题:

image.png

报错原因:

当为执行应用程序分配的内存小于运行应用程序所需的内存时,会出现此错误。

默认情况下,Node.js 的内存限制是 512 mb,要解决这个问题,需要使用命令max-old-space-size增加内存限制,可以避免内存限制问题。

node --max-old-space-size=1024 index.js #increase to 1gb
node --max-old-space-size=2048 index.js #increase to 2gb  
node --max-old-space-size=3072 index.js #increase to 3gb  
node --max-old-space-size=4096 index.js #increase to 4gb  
node --max-old-space-size=5120 index.js #increase to 5gb  
node --max-old-space-size=6144 index.js #increase to 6gb  
node --max-old-space-size=7168 index.js #increase to 7gb  
node --max-old-space-size=8192 index.js #increase to 8gb

解决方案:

"scripts": {
    "build": "node --max_old_space_size=8192 node_modules/vite/bin/vite.js build",
}

image.png

来源: