angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

AOT build fails due to "JavaScript heap out of memory"

Open ghost opened this issue 9 years ago • 427 comments

Bug Report or Feature Request (mark with an x)

- [X ] bug report -> please search issues before submitting
- [ ] feature request

Versions.

@angular/cli: 1.0.0
node: 7.7.4
os: win32 x64
@angular/animations: 4.0.0
@angular/common: 4.0.0
@angular/compiler: 4.0.0
@angular/core: 4.0.0
@angular/flex-layout: 2.0.0-rc.1
@angular/forms: 4.0.0
@angular/http: 4.0.0
@angular/material: 2.0.0-beta.2
@angular/platform-browser: 4.0.0
@angular/platform-browser-dynamic: 4.0.0
@angular/router: 4.0.0
@angular/cli: 1.0.0
@angular/compiler-cli: 4.0.0

Repro steps.

ng build --prod --aot

The log given by the failure.

/node_modules/@angular/material/aut 92% chunk asset optimization
<--- Last few GCs --->

[6328:0000016AB4D09F00]  1775597 ms: Mark-sweep 1411.2 (1513.5) -> 1411.0 (1513.5) MB, 1240.6 / 0.0 ms  last resort


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0000034B0DD266A1 <JS Object>
    2: optimize [0000000FABC02311 <undefined>:5480] [pc=00000082575652C8](this=000000633199A279 <an AST_Call with map 0000014753FA0291>,compressor=00000226DBDECA61 <a Compressor with map 0000032B1EC8F829>)
    3: before [0000000FABC02311 <undefined>:5463] [pc=0000008258C1818D](this=00000226DBDECA61 <a Compressor with map 0000032B1EC8F829>,node=000000633199A279 <an AST_Call with map 0000014753...

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

Desired functionality.

I would like to be able the app using AOT.

Mention any other details that might be useful.

I have tried changing ng.cmd to this:

@IF EXIST "%~dp0\node.exe" (
  "%~dp0\node.exe" --max_old_space_size=8192 "%~dp0\..\@angular\cli\bin\ng" %*
) ELSE (
  @SETLOCAL
  @SET PATHEXT=%PATHEXT:;.JS;=;%
  node --max_old_space_size=8192 "%~dp0\..\@angular\cli\bin\ng" %*
)

and ngc.cmd to:

@IF EXIST "%~dp0\node.exe" (
  "%~dp0\node.exe" --max_old_space_size=8192 "%~dp0\..\@angular\compiler-cli\src\main.js" %*
) ELSE (
  @SETLOCAL
  @SET PATHEXT=%PATHEXT:;.JS;=;%
  node --max_old_space_size=8192 "%~dp0\..\@angular\compiler-cli\src\main.js" %*
)

I have 8GB swap file. The build fails after 20-25 minutes standing on 92% progress.

ghost avatar Mar 24 '17 09:03 ghost

I am also having the same issue. I can share my code to you @filipesilva

dobrinsky avatar Nov 28 '17 17:11 dobrinsky

My --prod build works but slow. When I added --stats-json it ran out of memory. I got it working by doing this:

"build:prod:myapp:stats": "node --max_old_space_size=4096 node_modules/@angular/cli/bin/ng build --prod --app=myapp --stats-json"

dereklin avatar Nov 30 '17 01:11 dereklin

We're updating the Webpack version used in the CLI in https://github.com/angular/angular-cli/pull/8689 to include the fix for excessive memory usage in ModuleConcatenationPlugin (https://github.com/webpack/webpack/pull/5997).

This will be available in the next release of Angular CLI and should address most of the reports of excessive memory usage in 1.3.x and up.

I'd like to reiterate that it is expected that projects will reach the memory limit after a certain size. The bigger your project is, the more memory it will need to be built especially in --prod.

For those cases the recommendation is that you run the CLI with an increased memory limit via a npm script:

    "ng-high-mem": "node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng"

Then you can do npm run ng-high-mem -- build --prod to do a production build. Note the double dash (--), it is used in npm scripts to separate args.

In this script the limit is increased to 8gigs. You can use a bigger number if you need.

Meanwhile we will keep on making improvements to reduce the memory footprint of the Angular CLI build system.

@changLiuUNSW I've opened a separate issue to track the excessive build time increase when using --build-optimizer: https://github.com/angular/devkit/issues/305.

filipesilva avatar Nov 30 '17 15:11 filipesilva

Thanks for taking the time to look into this in such detail @filipesilva! Much appreciated!

radoslavpetranov avatar Nov 30 '17 15:11 radoslavpetranov

The problem is, this is my webpack.config:

`const path = require('path'); const webpack = require('webpack'); const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin; const merge = require('webpack-merge'); const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => { // Configuration in common to both client-side and server-side bundles //const isDevBuild = !(env && env.prod); const isDevBuild = true; const sharedConfig = { stats: { modules: false }, context: __dirname, resolve: { extensions: [ '.js', '.ts' ] }, output: { filename: '[name].js', publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix }, module: { rules: [ { test: /.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' }, { test: /.html$/, use: 'html-loader?minimize=false' }, { test: /.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] }, { test: /.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' } ] }, plugins: [new CheckerPlugin()] };

// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
    entry: { 'main-client': './ClientApp/boot.browser.ts' },
    output: { path: path.join(__dirname, clientBundleOutputDir) },
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./wwwroot/dist/vendor-manifest.json')
        })
    ].concat(isDevBuild ? [
        // Plugins that apply in development builds only
        new webpack.SourceMapDevToolPlugin({
            filename: '[file].map', // Remove this line if you prefer inline source maps
            moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
        })
    ] : [
        // Plugins that apply in production builds only
        new webpack.optimize.UglifyJsPlugin(),
        new AngularCompilerPlugin({
            tsConfigPath: './tsconfig.json',
            entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
            exclude: ['./**/*.server.ts']
        })
    ])
});

// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig, {
    resolve: { mainFields: ['main'] },
    entry: { 'main-server': './ClientApp/boot.server.ts' },
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./ClientApp/dist/vendor-manifest.json'),
            sourceType: 'commonjs2',
            name: './vendor'
        })
    ].concat(isDevBuild ? [] : [
        // Plugins that apply in production builds only
        new AngularCompilerPlugin({
            tsConfigPath: './tsconfig.json',
            entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
            exclude: ['./**/*.browser.ts']
        })
    ]),
    output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, './ClientApp/dist')
    },
    target: 'node',
    devtool: 'inline-source-map'
});

return [clientBundleConfig, serverBundleConfig];

}; `

So, I am not using ModuleConcatenationPlugin and I still get the same error. That is why I offered my code

dobrinsky avatar Nov 30 '17 16:11 dobrinsky

@dobrinsky how many TS files do you have in your project? Do you know what is peak memory usage?

filipesilva avatar Nov 30 '17 16:11 filipesilva

I have 240. Will get up to 400 probably until I finish the project.

No, I do not know. I am a beginner...I do not know how to find that out

dobrinsky avatar Nov 30 '17 16:11 dobrinsky

I usually run the build process, and then just look at the task manager to see how much memory the process is using. Peak memory usage is just the biggest number I saw for memory usage while the process was running.

filipesilva avatar Nov 30 '17 16:11 filipesilva

:)))) I didn't knew it was that simple. Thought I need some software or something...

Anyway, the strangest thing happened:

I started with:

image

Then Visual Studio started using memory in the build process:

image

Then of course, Node started using too:

image

But my peak was 68%, with just 1.67 GB of memory usage

So, this is definitely something else

dobrinsky avatar Nov 30 '17 16:11 dobrinsky

Upgrading to Angular-CLI 1.5.5, Node to 8.9.1 and Yarn to 1.3.2 Fixed that issue for me. And running Yarn did the fix better than npm.

nadhir-falta avatar Nov 30 '17 16:11 nadhir-falta

I am not using Yarn. I have Node 9.2, but Angular-CLI 1.5.4.

I will try with 1.5.5

dobrinsky avatar Nov 30 '17 20:11 dobrinsky

Thanks @filipesilva for your post above re: "ng-high-mem". I confirmed with my project that this does work and I no longer run out of memory during prod build with aot and build-optimizer on. Without this I ran out of memory.

package.json scripts: "ng-high-mem": "node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng" Now this works: npm run ng-high-mem -- build --prod --aot=true --build-optimizer=true

Note in your msg above you wrote: "Then you can do npm run ng-high-mem -- --prod to do a production build." But I think you missed "build" in there: npm run ng-high-mem -- build --prod

JasonPaape avatar Nov 30 '17 23:11 JasonPaape

Hi @filipesilva,

In our project we are having the out of memory issue with below version @angular/cli: 1.2.0 @angular: 4.2.5

We are near production and we expect solution for this. Due to some constraints we couldn't able to migrate to angular 5 for now.

Is there any solution will be available for this?

Jayaraj8905 avatar Dec 01 '17 07:12 Jayaraj8905

@dobrinsky have you tried running your webpack config with node --max_old_space_size=8192 to increase the memory limit? What is the maximum you see then? If it's just above the maximum you saw before it might just be that you need that little extra bit of memory.

@JasonPaape thanks, I added it now!

@Jayaraj8905 at this point your best bet is to either use that script (ng-high-mem) or update. 1.2.0 was a long time ago and we don't publish fixes for it anymore.

filipesilva avatar Dec 01 '17 08:12 filipesilva

Using ng-high-mem option with @angular/cli 1.5.4 solved it for me. Using @angular/cli 1.5.5, I saw 30-40% less memory usage, but still memory outage, so still ng-high-mem required for my build.

Now using ng-high-mem (with 8192) it is using a lot more memory. Is it using more when it has more memory available?

JaapMosselman avatar Dec 01 '17 14:12 JaapMosselman

Please bear in mind that the webpack update is not in yet. It will be in either 1.5.6 or 1.6.0.

filipesilva avatar Dec 01 '17 14:12 filipesilva

Hopefully that will also speed up the production build a lot. I just migrated from the old Angular 2 way (ngc aot + rollup) to angular/cli and the build time grow from 4m to about 12m. :-(

JaapMosselman avatar Dec 01 '17 19:12 JaapMosselman

I'm seeing this since the migration to angular 5 + angular-cli 1.5.5 on my CI build machine. Thanks for the help of appveyor team I was able to use the --max_old_space_size on the node cmd file. Relevant info can be found in the following discussion (which links here): https://help.appveyor.com/discussions/problems/10192-out-of-memory-when-using-angular-cli-15-angular-5 And in this issue in my repository. https://github.com/IsraelHikingMap/Site/pull/567

HarelM avatar Dec 01 '17 21:12 HarelM

I have a same issue with @angular/[email protected]

ng build -prod
 95% emitting                                                                             
<--- Last few GCs --->

  113209 ms: Mark-sweep 853.8 (1439.3) -> 857.6 (1439.3) MB, 271.2 / 0.0 ms [allocation failure] [scavenge might not succeed].
  113472 ms: Mark-sweep 857.6 (1439.3) -> 861.5 (1439.3) MB, 263.2 / 0.0 ms [allocation failure] [scavenge might not succeed].
  113756 ms: Mark-sweep 861.5 (1439.3) -> 876.5 (1423.3) MB, 284.4 / 0.0 ms [last resort gc].
  114039 ms: Mark-sweep 876.5 (1423.3) -> 891.6 (1423.3) MB, 282.5 / 0.0 ms [last resort gc].


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x31d99d6cfb51 <JS Object>
    1: DoJoin(aka DoJoin) [native array.js:~129] [pc=0xc7b98c68639] (this=0x31d99d604381 <undefined>,w=0x23bc0f2ffd31 <JS Array[590]>,x=590,N=0x31d99d6043c1 <true>,J=0x31d99d6ae4d1 <String[1]:  >,I=0x31d99d6b46e1 <JS Function ConvertToString (SharedFunctionInfo 0x31d99d652dc9)>)
    2: Join(aka Join) [native array.js:180] [pc=0xc7b9864f2b2] (this=0x31d99d604381 <undefined>,w=0x23bc0f2ffd31 <JS ...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [ng]
 2: 0x10983ec [ng]
 3: v8::Utils::ReportApiFailure(char const*, char const*) [ng]
 4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [ng]
 5: v8::internal::Factory::NewRawTwoByteString(int, v8::internal::PretenureFlag) [ng]
 6: v8::internal::Runtime_StringBuilderJoin(int, v8::internal::Object**, v8::internal::Isolate*) [ng]
 7: 0xc7b939092a7
Aborted (core dumped)

kisdaniel avatar Dec 02 '17 23:12 kisdaniel

adding to this line "build-prod": "node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng build --prod", to package.json helped me.

kisdaniel avatar Dec 03 '17 08:12 kisdaniel