FATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap

有一个angular的项目,工程比较大,在一个内存为8G的笔记本上运行打包命令失败,报错:

FATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory

原因是内存不足,需要加大V8默认的内存限制

–max-old-space-size

以下内容来自http://nodejs.cn/api v18.7.0版本的说明

Sets the max memory size of V8’s old memory section. As memory consumption approaches the limit, V8 will spend more time on garbage collection in an effort to free unused memory.

翻译:设置 V8 旧内存部分的最大内存大小。 随着内存消耗接近极限,V8 会花更多的时间在垃圾回收上,以释放未使用的内存。

On a machine with 2 GiB of memory, consider setting this to 1536 (1.5 GiB) to leave some memory for other uses and avoid swapping.

$ node --max-old-space-size=1536 index.js

看网上有人给的建议是 添加 --max_old_space_size这个参数,不知道具体是什么原因,也没研究,这里采用的是–max-old-space-size

在VUE的项目中做过如下修改生效

在node_modules.bin下的webpack-dev-server 或者 webpack-dev-server.cmd 文件中添加 --max-old-space-size=4096,可以根据项目调整大小,添加到下图箭头所示位置
在这里插入图片描述

在angular项目中做的修改

1、 在package.json中scripts 部分运行node命令的地方都加上–max-old-space-size=4096

"scripts": {
    
    
    "dev": "ng serve --port 4200 --open",
    "dev:open": "ng serve --disableHostCheck --host 0.0.0.0 --port 4200 --open",
    "build": "ng build --prod --outputPath=dist/web --base-href=/web/",
    "build:dev": "node --max-old-space-size=4096 run.js dev & ng build --prod --outputPath=dist/web --base-href=/web/",
    "copy": "node node_modules/ng-zorro-iop/copy.js",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

2、在目录node_modules/.bin下的ng.cmd和ngc.cmd文件中,添加 --max-old-space-size=4096

扫描二维码关注公众号,回复: 15452089 查看本文章
@ECHO off
SETLOCAL
CALL :find_dp0

IF EXIST "%dp0%\node.exe" (
  SET "_prog=%dp0%\node.exe"
) ELSE (
  SET "_prog=node"
  SET PATHEXT=%PATHEXT:;.JS;=;%
)

"%_prog%" --max-old-space-size=4096 "%dp0%\..\@angular\cli\bin\ng" %*
ENDLOCAL
EXIT /b %errorlevel%
:find_dp0
SET dp0=%~dp0
EXIT /b

猜你喜欢

转载自blog.csdn.net/small_tu/article/details/126528652
今日推荐