Angular ng build causes out of memory while building


While building angular code using ng build command or ng start command one can get an out-of-memory or low memory error. This can occur in a system with lower RAM or even in those with higher RAM.

When I run ng build on my server, during the Generating browser application bundles (phase: building)… message, eventually I get an out-of-memory crash. This actually happens on my server, which has 2GB of RAM, as well as on my development machine, which has 16GB of RAM.

ng build causes out of memory · Issue #19526 · angular/angular-cli (github.com)

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed – JavaScript heap out of memory after Angular 7.1 upgrade. The previous version 6.1 was working perfectly fine.

There might be one or more causes for this and this totally depends upon the version and used libraries. To fix this error one can try the following methods to increase heap memory for nodejs.

The first and most common thing you could try is using the node option –max_old_space_size parameter with higher memory size.

This Node option sets memory used by node js process should be a maximum 3/4th of available memory.

How to use it?

You can set this option using several methods and you can use any of this or you can find another one.

node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng build --prod

ng node --max_old_space_size=4096 && ng build --prod

On Mac and Linux you can do this by NODE_OPTION environment variables.

export NODE_OPTIONS=--max_old_space_size=8192

Or you can set permanently add the above to .zshrc file in Mac and .bashrc file in Linux inside the home folder.

On windows temporarily you can set environment variables using SET command or adding NODE_OPTIONS to the environment variables.

SET NODE_OPTIONS=--max_old_space_size=8192

This can also be done in scrip inside package.json file.

Open package.json

Add this code inside scripts

"build-prod": "node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng build --prod"

On terminal run as follows

>npm run build-prod

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.