How to solve JavaScript heap out of memory in ionic build –prod

Lately, I was facing JavaScript heap out of memory issue whenever I tried to make Ionic 3 production build. After some googling, I found out that I am not the only one facing this issue. See this thread.

Cause of JavaScript heap out of memory error

Ionic 3 is based on angular, and it uses ng, which in itself uses webpack tool, command for build process. `ng` build command uses additional processes for –prod that includes AOT compiling, Minifying JS, Minifying CSS, and Linting. These processes are memory hungry and as your project starts adding more and more components, it consumes all the memory allowed for JavaScript heap. This becomes more expensive with extra comments and unused code in your project.

Typically NodeJs runtime is allowed to take 4GB of RAM and you can increase it by --max-old-space-size command. To increase --max-old-space-size to 8 GB, add ionic:build in scripts tag of package.json file as shown below:

//in package.json, add this line in scripts array after build 
"ionic:build": "node --max-old-space-size=8192 ./node_modules/@ionic/app-scripts/bin/ionic-app-scripts.js build"

//like
,
"scripts": {
    "start": "ionic-app-scripts serve",
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build": "node --max-old-space-size=8192 ./node_modules/@ionic/app-scripts/bin/ionic-app-scripts.js build",
    "lint": "ionic-app-scripts lint"
  },

Now simply run ionic build –prod from terminal, and it should do the job.

ionic build --prod

Leave a Reply

%d bloggers like this: