Increased main.js bundle size but less lazy chunks after updating to angular 9.0.0-rc.1
π Bug report
Command (mark with an x)
- [ ] new
- [x] build
- [ ] serve
- [ ] test
- [ ] e2e
- [ ] generate
- [ ] add
- [ ] update
- [ ] lint
- [ ] xi18n
- [ ] run
- [ ] config
- [ ] help
- [ ] version
- [ ] doc
Description
After updating from Angular 8.2.3 to 9.0.0-rc.1 the bundle size was increased for main module and some of the feature modules:
Before it was:
After updating to Angular 9.0.0-rc.1 it is

π¬ Minimal Reproduction
running ng build --prod --namedChunks with following configuration:
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"commonChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "1mb",
"maximumError": "2mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
}
],
"serviceWorker": true,
"ngswConfigPath": "ngsw-config.json"
}
}
π Your Environment
Angular CLI: 9.0.0-rc.1
Node: 10.15.3
OS: win32 x64
Angular: 9.0.0-rc.1
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router, service-worker
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.900.0-rc.1
@angular-devkit/build-angular 0.900.0-rc.1
@angular-devkit/build-optimizer 0.900.0-rc.1
@angular-devkit/build-webpack 0.900.0-rc.1
@angular-devkit/core 9.0.0-rc.1
@angular-devkit/schematics 9.0.0-rc.1
@angular/cdk 8.2.3
@angular/material 8.2.3
@ngtools/webpack 9.0.0-rc.1
@schematics/angular 9.0.0-rc.1
@schematics/update 0.900.0-rc.1
rxjs 6.5.3
typescript 3.6.4
webpack 4.41.2
@filipesilva I can see also a total size reduction but main.js is bigger. I personally thought main.js will be smaller because this has to be loaded upfront and I canβt work much around besides removing libs. But now we got 200-300kb additional into our main bundle by only updating to version 9. We worked hard to reduce main bundle size and now angular itself pushed 300kb into the main bundle. All these size reduction showcases are just for hello world apps but invalid for real world apps. I think this issue can be closed as this behavior seems to be expected. It should be pinned as many people will realize this and will ask why.
@elvirdolic keep in mind that if Ivy isn't working well for you, you can disable as described in https://next.angular.io/guide/ivy#opting-out-of-ivy-in-version-9. That should get you back to View Engine, which was the default in version 8.
@filipesilva yes, Ivy significantly decrease size. Maybe that's why material components grows so significantly to increase main bundle size.
@Splaktar tired to migrate with ng update and with --migrate only too. Both fails for me. but ng update for core and cli at my project fails at some migration step too...
@parys thank you for the reproduction. I was able to create 2 issues based on it
- https://github.com/angular/components/issues/17765
- https://github.com/angular/components/issues/17764
I've looked into this and have arrived at a minimal reproduction and explanation in https://github.com/filipesilva/factory-code-location
Factory code location differences between Ivy and View Engine
This application contains the following structure:
- a shared ngmodule called
SharedModulecontaining a component calledSharedComponent - two lazy routes (
lazy-oneandlazy-two) that importSharedModuleand useSharedComponent - a root
AppModulethat also importsSharedModule SharedComponentis not used by any template outside the lazy routes
You can change between Ivy and VE by flipping the "enableIvy": true, switch in tsconfig.json.
Running ng build --prod with Ivy shows the following bundles:
chunk {0} runtime.js, runtime.js.map (runtime) 2.23 kB [entry] [rendered]
chunk {1} main.js, main.js.map (main) 262 kB [initial] [rendered]
chunk {2} polyfills.js, polyfills.js.map (polyfills) 36 kB [initial] [rendered]
chunk {3} styles.css, styles.css.map (styles) 38 bytes [initial] [rendered]
chunk {4} 4.js, 4.js.map () 852 bytes [rendered]
chunk {5} 5.js, 5.js.map () 852 bytes [rendered]
Date: 2019-11-22T14:22:51.177Z - Hash: f09b623e86f3d80f4000 - Time: 33745ms
Running ng build --prod with VE shows the following bundles:
chunk {0} runtime.js, runtime.js.map (runtime) 2.24 kB [entry] [rendered]
chunk {1} common.js, common.js.map (common) 530 bytes [rendered]
chunk {2} main.js, main.js.map (main) 263 kB [initial] [rendered]
chunk {3} polyfills.js, polyfills.js.map (polyfills) 36 kB [initial] [rendered]
chunk {4} styles.css, styles.css.map (styles) 38 bytes [initial] [rendered]
chunk {5} 5.js, 5.js.map () 1.17 kB [rendered]
chunk {6} 6.js, 6.js.map () 1.17 kB [rendered]
Date: 2019-11-22T14:23:43.985Z - Hash: 90d6a92b420719382f49 - Time: 30408ms
The main difference is the common.js bundle.
In VE this bundle contains the template factory for SharedComponent ("shared-component works!").
In Ivy this template factory is in main.js instead.
However, Ivy will also have the common.js If you remove the SharedModule import from AppModule.
What's happening
To understand what's happening it is important to understand one important difference between Ivy and VE:
- in VE, compiling a component would generate two files: the original transpiled file and a
.ngfactory.jsfile containing the template factory - in Ivy, compiling a component generates only the original transpiled file
In this example SharedComponent is imported via SharedModule both through static imports in AppModule and in the lazy loaded modules.
However, it is not used in any templates outside of lazy routes.
This leads to the following difference between Ivy and VE:
- in VE, the original
SharedComponentclass is inmain.jsbut the.ngfactory.jsfile is incommon.js - in Ivy, there is only the original
SharedComponentclass inmain.js
If you remove the static import for SharedModule in AppModule there is no longer a chain of static imports in the main module for SharedComponent so it will always be in common.js, even in Ivy.
What you can do right now
If you find that with Ivy your main bundle gets larger while the other bundles get smaller, verify that the components and ngmodules that you want to be lazy loaded are only imported in lazy modules. Anything that you import outside lazy modules can end up in the main bundle.
Meanwhile we'll try to figure out if there's something we can do in Angular itself to help.
Hi @filipesilva
thanks a lot for your response
I think it is not only related to the share module, in the source-map I gave in https://github.com/angular/angular/issues/33881#issuecomment-556970609 almost every module's bundle size has increased(including @angular/core and @angular/common)
@vthinkxie there is indeed another case, where Angular third party libraries go up in size, that I'm still looking into. We have a good reproduction for that one that I'm analysing in https://github.com/filipesilva/aio-ivy-ve/tree/master/aio.
@filipesilva The factory location example is interesting.
If compiled in Ivy production AOT, without enabling the option to keep the JIT metadata around, then nothing in main.js should reference the shared component, which would make it conceptually eligible to be moved to the common chunk. I downloaded your factory location reproducer repo, and checked the output. Sure enough, nothing in main.js does reference the shared component class, except itself.
The problem is that although everything in the shared.component.ts module is pure, and gets marked as such by buildOptimizer, webpack does not know realize the shared.component.ts module as a whole is side effect free, so it is unable to remove the import statement present in shared.module.ts, because it thinks there might be side effects. Therefore, when it decides what modules go in which chunks, it it needs to keep the shared-component.ts module in the main chunk too.
If webpack knew shared.component.ts was side effect free, it would have put the whole component in common.
Indeed if I roll back to using rc2, and add inform webpack that typescript files inside src/app donβt have side effects by adding the following as src/app/package.json then the component does end up in the common chunk, even though the app module imports the shared module:
{
"sideEffects": [
"**/*.css"
]
}
Now, why did I say roll back to rc2? Because starting in rc3, BuildOptimizer no longer removes ngSetModuleScope, relying on terser to remove it. Unfortunately terser runs after the chunks have been split, so webpack will think that shared.module.ts is using SharedComponent. This is due to PR #16228, obviously.
It would obviously be nice if there were some some webpack plugin that could attempt to automatically determine if a module has side effects, ideally taking the pure comments into account. Of course that is one of the major things rollup does that webpack does not.
@KevinCathcart you're quite right about everything you mentioned but it's important to note that application code being free from (toplevel) side effects is the main part here.
If app code is free from side effects then it becomes safe to elide imports that aren't used in the transpiled code. If it's not free from side effects, then it's not safe to elide.
Build Optimizer doesn't mark shared.component.ts module as pure in this case though. Rather, ngc compilation adds code to it that is marked as pure. But the ES module itself is not necessarily pure. Another PR referred to in the one you mentioned talks about this a bit more https://github.com/angular/angular/pull/33337#issuecomment-555948255.
After ascertaining an ES module is free from side effects, the bundler might be able to remove imports to it if no references are used. But we cannot assume app code is free from side effects.
The ngSetModuleScope change you mentioned is interesting. I removed it because https://github.com/angular/angular/pull/33671 instead gates it on a global flag called ngJitMode mode, and removes the pure comment. It still does no favors for webpack because webpack doesn't interpret the global value anyway. Come to think of it I don't think it does rollup any favors either though, since rollup itself doesn't have a way to define global values (I think?). But I think it's still correct because Ι΅Ι΅setNgModuleScope being retained is only determined by that flag, not of optimizations being turned on.
That reproduction I put up was a bit simplistic though, and only focused on illustrating the exact minimal code to see the problem. If you're curious about the real case that led me there, it's https://github.com/kubernetes/dashboard. Here ComponentsModule imports SharedModule and both include a bunch of components and material modules. Then ComponentsModule is only used in lazy routes.... and on LoginModule, which isn't lazy and also uses a couple. So in this case some of the shared components are indeed used eagerly. I think it doesn't change much overall though.
Hi, @filipesilva any update on this? could this issue resolve before angular 9 final release?
Can the need: repro steps label be removed or are you still looking for reproductions?
@vthinkxie it's marked as a v9 blocker atm, so hopefully... @filipesilva is that milestone still correct?
We're just waiting on some styling compiler changes before reacessing, but we have been keeping track of how it changed over every RC.
Heya all,
We've been working on addressing the remaining size discrepancies and now believe that Ivy bundles should now in all common scenarios be either smaller or on par with View Engine (the previous compiler) bundles as of RC 11 of Angular Framework and CLI.
If you see your bundles increasing in size with Ivy, we want to know. Please open a new issue with a reproduction if possible. If you canβt publicly share your reproduction, consider sharing it privately instead.
Thanks to everyone that has spent time and energy producing the repos, theyβve been invaluable tracking down these last bugs!
@filipesilva our main went from 2MB to 2.2MB after upgrade. Overall size reduction is massive but the main is bigger :). If you can guide me what do you need, I could help to create a reproduction.
Overall size reduction is massive but the main is bigger :)
I recently switched to the ES/ivy way of importing the lazy module and I noticed the same issue you described (main bundle got bigger, lazy bundle got smaller, so some code got moved to main bundle from the lazy one). But I got the expected behavior back by explicitly telling the webpack that I want _db-view module to be put into a separate chunk.
So if you load the lazy module using old/deprecated way, using NgModuleFactoryLoader.load("./_db-view/db-view.module#DbViewModule") + AngularCompilerPlugin.additionalLazyModules, then the entire lazy module gets automatically put into a separate chunk. But if you use ES importing you have to tweak the webpack's optimization.splitChunks config to get entire lazy module to be put in a separate chunk, at lest in my case.
Not sure this info will be helpful to someone since I don't use Angular CLI in the referenced project but use AngularCompilerPlugin directly.
@elvirdolic I'm currently following up on this in https://github.com/angular/angular-cli/issues/16866. If you could provide me with a repro, even privately, I could take a look.
@vladimiry I'm very interested in what you're doing! Can you give me a bit more context please? I didn't quite follow. An example would be super cool too!
@filipesilva, I just described the use of chunks splitting webpack's feature.
See 4 different output listings using angular v9.0.0:
- ES import of
_db-viewmodule (notice_db-view.jshas not been created, ie all the custom app code is put into singleindex.jschunk)
573964 index.js
4438375 vendor.js
- ES import of
_db-viewmodule + AngularCompilerPlugin.additionalLazyModules (only single module file is put into a separate_db-view.jschunk, not the whole module)
4011 _db-view.js
577075 index.js
4438375 vendor.js
- ES import of
_db-viewmodule + putting_db-viewmodule/folder to a separate_db-view.jschunk by tweaking the optimization.splitChunks.cacheGroups config:
131362 _db-view.js
442694 index.js
4438375 vendor.js
NgModuleFactoryLoader.load("./_db-view/db-view.module#DbViewModule")+ AngularCompilerPlugin.additionalLazyModules:
133796 _db-view.js
442564 index.js
4438375 vendor.js
So if NgModuleFactoryLoader.load("./_db-view/db-view.module#DbViewModule") + AngularCompilerPlugin.additionalLazyModules used then there is no need to tweak the webpack config. But if you switch to the ES import the webpack config needs to be adjusted in order to put entire _db-view module/folder into a separate _db-view.js chunk.
@vladimiry not super sure what's happening there. That would make sense if you were not using Ivy though.
You had const {DbViewModule} = await import("src/web/browser-window/app/_db-view/db-view.module"); as the ES dynamic import. But with VE, we don't recognize this imports properly everywhere. In fact, we only recognize this format:
https://github.com/angular/angular-cli/blob/60918794287542b4f5aabfdf195089ea8d357f37/packages/ngtools/webpack/src/transformers/import_factory.ts#L107-L114
But I think you were using Ivy in your example? So that's really weird.
@filipesilva, the comment you referenced seems to be related to rewriting the Route definitions during the compiling stage. But I was describing the case of lazy-loading the Angular module without using the Route-thing, just dynamic lazy-loading the module from any point of the app.
But I think you were using Ivy in your example?
Yes, Ivy enabled there starting from some Angular v8 version.
Tried to reproduce by doing this:
ng new latest-app --routing && cd latest-appng generate module lazy --route lazy --module app.moduleng build --prod, saw a lazy chunk with 751 bytes- added
"lazyModules": ["src/app/lazy/lazy.module.ts"]to my build options- this passes it on to
AngularCompilerPlugin.additionalLazyModules
- this passes it on to
- built again, saw a lazy chunk with 751 bytes
- replaced the ES dynamic import with
NgModuleFactoryLoader.loadinsrc/app/app-routing.module.ts
const routes: Routes = [
// { path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];
NgModuleFactoryLoader.load('./lazy/lazy.module#LazyModule');
- built again, saw error:
ERROR in src/app/app-routing.module.ts:16:23 - error TS2339: Property 'load' does not exist on type 'typeof NgModuleFactoryLoader'.
16 NgModuleFactoryLoader.load('./lazy/lazy.module#LazyModule');
- reverted the previous change, opened
node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.jsand manually changed the cache groups
cacheGroups: {
default: !!commonChunk && {
chunks: 'async',
minChunks: 2,
priority: 10,
},
common: !!commonChunk && {
name: 'common',
chunks: 'async',
minChunks: 2,
enforce: true,
priority: 5,
},
vendors: false,
vendor: !!vendorChunk && {
name: 'vendor',
chunks: 'initial',
enforce: true,
test: (module, chunks) => {
const moduleName = module.nameForCondition ? module.nameForCondition() : '';
return /[\\/]node_modules[\\/]/.test(moduleName)
&& !chunks.some(({ name }) => utils_1.isPolyfillsEntry(name)
|| globalStylesBundleNames.includes(name));
},
},
"lazy": {
test: /src[\\/]app[\\/]lazy/,
name: "lazy",
chunks: "all",
},
},
- built again, saw a lazy chunk with 751 bytes
So I'm really confused by the behaviour you're seeing. I don't understand how you could use NgModuleFactoryLoader.load at all, and I can't imagine how these bundles could be any different when using Ivy.
Any chance you could give me a repro, or instructions on how to build your repo and what changes to make to see this behaviour?