JavaScript heap out of memory

Heap out of memory? As a web developer, you might have come across a situation when you Angular application build fails with the message ‘ng build fail with ‘JavaScript heap out of memory’.

javascript-heap-out-of-memory

The main issue is production builds are taking longer, which usually indicated that more code is being processed and more memory is needed.

The general issue for running out of memory is as projects grow bigger, they use more memory, and might need to increase the default memory limit.

Increasing the memory limit is not a hack, and something you should expect to do at some point. Node processes have a default memory limit of about 1.7gigs. When a node process starts getting close to the memory limit it needs to spend more and more time doing garbage collection to free up memory, which in turn makes it run more slowly. Bigger projects will use up more memory than smaller projects so at some point a project will hit the memory limit.

What is the best way to fix JavaScript heap out of memory?

Hope you might have got the error like the following. This effectively saying “Your build ran out of memory”

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

The best way to fix the JavaScript heap out of memory issue is to use npm script. The following lines of code we can add in our application files to solve the issue. First line of code to be added is in the package.json as following

"ng-high-memory": "node --max_old_space_size=4000 ./node_modules/@angular/cli/bin/ng",
 

You can add the above code in the package.json file

"scripts": {
    "ng-high-memory": "node --max_old_space_size=4000 ./node_modules/@angular/cli/bin/ng",
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

–max_old_space_size value (in mega bites) can be used based on the requirement. Then for locally building/ creating dist folder, you will have to run the following command.

 npm run ng-high-memory build  --build-optimizer -env=dev 

Using Jenkins for Build?

When you are using jenkins for application build, you will have to add the JavaScript heap out of memory fixes in jenkins file.

sh 'npm run ng-high-memory build --build-optimizer -env=dev'

Sometimes, while building, you may come across the issue of npm not installing properly and the build fails. In order to avoid this situation, we can use the following method.

 sh 'npm install && npm run ng-high-memory build --build-optimizer -env=dev' 

So this will run npm install command and then use the memory limit mentioned in the package.

Hope this help you to fix the javascript Heap out of memory issue on your angular project. To know more about angular-cli, please click.

label, , , , , ,

About the author