Angular 7 - JavaScript 堆内存不足错误

Ask*_*_SO 2 javascript node.js angular angular7

在 Angular 7 应用程序中,当我执行 ng serve 命令时,它会抛出“JavaScript heap out of memory”错误。

从不同的 SO 答案中,我可以理解问题是由于对 Node.js 的内存分配不足。正如他们的回答中提到的,通过执行以下命令,我可以编译/构建 angular 应用程序。

node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng serve
Run Code Online (Sandbox Code Playgroud)

但是我需要在 package.json 或一些配置文件中编写这个内存分配代码,这样我就不需要每次都执行整个命令。同样期待,代码逻辑应该适用于所有环境,并且在更高的环境中构建期间不应产生任何问题。

有人可以帮我解决这个问题。下面是我的 package.json 代码。

"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.config.json",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
Run Code Online (Sandbox Code Playgroud)

Imr*_*bar 5

First run This:

 npm install -g increase-memory-limit 
Run Code Online (Sandbox Code Playgroud)

Then add this line on your package.json file:

"myCustomMemoryComm ": "node --max_old_space_size=8000 ./node_modules/@angular/cli/bin/ng"
Run Code Online (Sandbox Code Playgroud)

Like this:

"scripts": {
            "ng": "ng",
            "start": "ng serve --proxy-config proxy.config.json",
            "build": "ng build",
            "test": "ng test",
            "lint": "ng lint",
            "e2e": "ng e2e",
            "myCustomMemoryComm": "node --max_old_space_size=8000 ./node_modules/@angular/cli/bin/ng"
          },
Run Code Online (Sandbox Code Playgroud)

Then your further command will be every time for running the project (serve):

npm run myCustomMemoryComm -serve
Run Code Online (Sandbox Code Playgroud)

Or Direct Run this on console:

 node --max_old_space_size=8000 ./node_modules/@angular/cli/bin/ng
Run Code Online (Sandbox Code Playgroud)

And For Production build:

  node --max_old_space_size=4096 node_modules/@angular/cli/bin/ng build --baseHref=/your-project-name/ --prod=true
Run Code Online (Sandbox Code Playgroud)