Help Center/ CodeArts Build/ FAQs/ Using npm for Build/ JavaScript heap out of memory
Updated on 2023-11-28 GMT+08:00

JavaScript heap out of memory

Symptoms

When the npm build task is executed, the following error information is displayed in the log:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.

Cause Analysis

The memory used by the Node.js runtime is limited: 1.4 GB for a 64-bit system and 0.7 GB for a 32-bit system. The memory used in the current build has exceeded the default-allowed size.

Solution

Method 1: Upgrade the Node.js version.

Method 2: Set the --max_old_space_size or --max_new_space_size parameter when starting the node to adjust the memory usage limit.

node --max_old_space_size=1700 test.js // The unit is MB. Modifies the old memory limit.
node --max_new_space_size=1024 test.js // The unit is KB. Modifies the new memory limit.

The solutions for the three major front-end frameworks are as follows:

Frame

Solution

Vue

You only need to change the value of build in the package.json file and add the node command with parameters to the command. For example:

"build": "node --max_old_space_size=4096 build/build.js"

React

Assume that the content of the scripts field in the package.json file is as follows:

"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}

The actual code that works in the npm run build command is react-scripts build. Open the node_modules folder in the root directory of a project, find and open the .bin directory, find and open the react-scripts file, and add max_old_space_size=4096 to #!/usr/bin/env node:

#!/usr/bin/env node --max_old_space_size=4096

Angular

Assume that the content of the scripts field in the package.json file is as follows:

"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
}

Similar to React, the ng file exists in the .bin directory in the mode_modules folder in the root directory of a project. Modify the first line of the file.

#!/usr/bin/env  node --max_old_space_size=4096