Skip to content

Creating unnecessary excessive chunks #27715

Open

Description

@ChristopherPHolder

Command

build

Is this a regression?

  • Yes, this behavior used to work in the previous version

The previous version in which this bug was not present was

No response

Description

Disclaimer

This is not really a bug, as even if it worked differently with webpack, for esbuild this is normal. However, since the default bundler is now esbuild some would consider this a regression.

Required chunks references in dynamic imported code get split in to separate chunks

When splitting code, esbuild does not seems to properly take into account what is already statically imported (thus "required") and does not need to be split into a separate chunk.

To illustrate this lets consider an example where we have the following 5 standalone components:

  • AppComponent (The root component which is not lazy loaded)
  • Feature1Component (A feature component lazy loaded via a dynamic import in the router)
  • Feature21Component (A feature component lazy loaded via a dynamic import in the router)
  • Ui1Component (A UI component imported statically, like a button)
  • Ui2Component (A UI component imported statically, like a button)

Chunks without Shared Components

If the AppComponent has a RouterOutlet which has separate paths Feature1Component and Feature21Component it will generate a chunk for the code shared between these components (lets call it Common Chunk).

In this case the build output is:

Initial chunk files Names
chunk-YIKH6UD4.js - ("common")
main-V6UA4PHT.js main
Lazy chunk files Names
feature-1.component-AQEBZKLJ.js feature-1-component
feature-2.component-EH7EGWEP.js feature-2-component

And if Feature1Component imports Ui1Component and Feature21Component imports Ui2Component then code from Ui1Component will be bundle in Feature1Component and the code from Ui2Component will be bundle in Feature2Component.

Chunks with Shared Components

However, if the AppComponent also imports Ui1Component and Ui2Component this code is now shared and will be split into separate chunks.

Thus the build output will now be:

Initial chunk files Names
chunk-YIKH6UD4.js - ("common")
main-V6UA4PHT.js main
chunk-WKA4CZR7.js - ("ui-1-component")
chunk-XCJUHD2B.js - ("ui-2-component")
Lazy chunk files Names
feature-1.component-AQEBZKLJ.js feature-1-component
feature-2.component-EH7EGWEP.js feature-2-component

The issue is that Ui1Component and Ui2Component are now statically imported in the AppComponent, and therefore belong in this common chunk. These chunks are statically imported in the "common" chunk and required for the application to bootstrap but are downloaded separately.

As they are always downloaded, splitting them does not seems to have a benefit, when Feature1Component or Feature2Component imports them, the request is cached and it should not make a difference if it over imports.

However, splitting them does have a downside, it increases the load time. Even tho in this example the consequences of a couple of extra chunks is meaningless in larger apps the consequence is very real.

If the application produces 100 or 200 initial chunks this will have a significant impact on the initial load time and LCP.

image

Even tho the a modern browser using http3 or http2 uses multiplexing it will still have an significant overhead downloading so many small chunks. We are currently calling this the chunk gap:

image

Additionally this issue will have a larger impact on older and slower devices.

Additional example of performance impact:

Avoiding Code Splitting Shared Code

It seems possible to avoid additional chunking in some cases by using barrel files.

For example if we create a barrel file that exports both Ui1Component and Ui2Component and only import them via that barrel file we are able to force esbuild to place the shared code into the "common" chunk.

So using:

// ./ui/index.ts

export * from './ui-1.component';
export * from './ui-2.component';

The build output will now be:

Initial chunk files Names
chunk-YIKH6UD4.js - ("common")
main-V6UA4PHT.js main
Lazy chunk files Names
feature-1.component-AQEBZKLJ.js feature-1-component
feature-2.component-EH7EGWEP.js feature-2-component

Note

In esbuild architecture documentation it explains that:

code splitting is implemented as an advanced form of tree shaking.

This means that doing so will partially optout of tree shaking.

For example if we add a Ui3Component and a Feature3Component.

And we add the Ui3Component to the barrel file:

// ./ui/index.ts

export * from './ui-1.component';
export * from './ui-2.component';
export * from './ui-3.component';

If the Ui3Component is never imported anywhere it will not increase the initial bundle.

However, if we reference the Ui3Component in Feature3Component (loading the Feature3Component in a lazy route), this will increase the initial bundle even if Ui3Component is not used in the AppComponent.

Minimal Reproduction

https://github.com/ChristopherPHolder/ng-esbuild-demo

Exception or Error

Shared Code Required in a root component or a root node of the node graph is bundle together.

Your Environment

Angular CLI: 17.3.5        
Node: 20.11.1              
Package Manager: npm 10.2.4
OS: win32 x64

Angular: 17.3.5
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1703.5
@angular-devkit/build-angular   17.3.5
@angular-devkit/core            17.3.5
@angular-devkit/schematics      17.3.5
@schematics/angular             17.3.5
ng-packagr                      17.3.0
rxjs                            7.8.1
typescript                      5.4.5
zone.js                         0.14.4

Anything else relevant?

No response

Activity

  1. alan-agius4 commented on Aug 30, 2024

    @alan-agius4
    Collaborator

    If you set both NG_BUILD_DEBUG_PERF and NG_BUILD_OPTIMIZE_CHUNKS to "1" or "true", the console will log the duration of the optimizations.

    Note: To avoid overlapping logs, you may need to disable progress logging using ng build --no-progress.

    If you don't see any changes in the chunk sizes, we'll need a reproduction to investigate further.

  2. sod commented on Sep 2, 2024

    @sod
    Contributor

    The NG_BUILD_OPTIMIZE_CHUNKS=1 is very nice and works as advertised. I'm probably going to use it, when we switch.

    We are still stuck on webpack though, as I can't get the esbuild variant to perform as good. Webpack has some incredible features like:

    1. Multiple initial "dependOn" chunks. This allows to extract parts of the code into another chunk that can be loaded first (similar to polyfills file) but with the trick, that the other chunks can reuse exports from it. This allows dependencies like tracking and errors tracking (like sentry) be loaded and executed first, while the browser is parsing the 2 megabyte app. This saves a couple of two digit milliseconds. We can simulate that by using the polyfills file and passing an reusable API via window., so not big deal, but:
    2. The custom webpack loader allowed to preload dependencies, so at the moment the app runs, everything is already in memory, allowing the app to render in a single swoop. The new es module style doesn't allow that, which causes the renderer to stop for every lazy chunk (like the route, the header, the footer).
    3. The () => import(/* webpackMode: "eager" */'./my-dependency') pattern from webpack is quite powerful, as with this you could force it to be included in the initial chunk, but not yet executed. This reduces the burden on the browser as it doesn't have to execute parts of the app initially, but the code will be ready asap when needed without loading extra chunks.

    (2) and (3) you kind of solved by partial hydration, but that is not yet supported without zone.js, so we are sticking to webpack right now.

  3. dimeloper commented on Sep 6, 2024

    @dimeloper

    @alan-agius4 I tried it once again using your debugging hint. This is the output I am getting having the optimiser enabled:

    DURATION[NG_READ_CONFIG]: 0.039898750s
    DURATION[NG_READ_CONFIG]: 0.055066417s
    DURATION[NG_CREATE_PROGRAM]: 4.416569292s
    DURATION[NG_ANALYZE_PROGRAM]: 5.477037292s
    DURATION[NG_FIND_AFFECTED]: 0.005789167s
    DURATION[NG_EMIT_TS]: 12.525402208s
    DURATION[NG_DIAGNOSTICS_TOTAL]: 2.308133416s
    DURATION[NG_EMIT_JS*]: 822.466522754s [count: 1875; avg: 0.438648812s; min: 0.003237000s; max: 1.184354959s]
    DURATION[NG_EMIT_JS*]: 822.466522754s [count: 1875; avg: 0.438648812s; min: 0.003237000s; max: 1.184354959s]
    chunk-UDIDPQ7Z.js (1:49305): Use of eval in "chunk-UDIDPQ7Z.js" is strongly discouraged as it poses security risks and may cause issues with minification.
    DURATION[OPTIMIZE_CHUNKS]: 7.984619542s
    

    As seen in the last line, it looks like the optimiser is enabled.

    However the amount of chunks remains unchanged (dist folder contains the normal build output and dist-optimized contains the one using the optimiser):
    CleanShot 2024-09-06 at 13 22 42

    Before switching to the application builder and ESBuild we used to have 326 chunks in total....

  4. alan-agius4 commented on Sep 12, 2024

    @alan-agius4
    Collaborator

    @dimeloper, unfortunately without a reproduction it’s hard to tell why the chunks count remained the same.

  5. ChristopherPHolder commented on Oct 28, 2024

    @ChristopherPHolder
    Author

    @dimeloper
    Ran a quick test on using the setup for the environmental variable you provided and i see it did not work. The issue that its not present for the angular builder or at least not present at the right time.

    But there is an easy fix, instead of providing it to the executor using the define options simply create a .env file and set the env there.

  6. tobias-lippert commented on Feb 11, 2025

    @tobias-lippert
    @ChristopherPHolder Could you please elaborate on how you fixed it with the env file because for me it doesn't make a difference when I define it in an env file.

    EDIT: I figured out how to define it and there is a difference but still > 700 chunks is not a great result.

  7. slak44 commented on Mar 24, 2025

    @slak44

    To add to this issue, I encountered situations where it's even more obvious how excessive the chunks are (angular 19.1).

    For example, if I have a file with a string constant that's used in a few places in my app:

    export const MY_USEFUL_SHARED_CONSTANT = 'some-useful-text';

    I get a chunk/module that looks like this:

    var e="some-useful-text";export{e as a};

    Which I think is absolute nonsense, there is no reason not to inline it and get rid of the chunk entirely.
    This should already be within the abilities of esbuild, since doing the exact same thing with a .json does actually inline the string (I am importing just the version field from package.json, and that doesn't generate a new module...)

  8. sod commented on Jun 24, 2025

    @sod
    Contributor

    Found this issue today GoogleChrome/lighthouse#16539. So those chunks may not necessarily ruin the performance for your customer, but lighthouse seems to punish you for every single javascript request as its mobile simulation adds it to the LCP and FCP metric, even if your SSR already returned visually complete DOM.

  9. DzmVasileusky commented on Aug 18, 2025

    @DzmVasileusky

    +1
    We have 276 initial chunks and most of them are < 1kb ungzipped. This is crazy, server waiting time is growing with each next chunk.

  10. anuj-scanova commented on Aug 18, 2025

    @anuj-scanova

    This seems to be the reason for the downfall of Angular. After using Angular for 10+ years, starting from AngularJS, we are now switching to another framework just because of this issue.
    After the recent upgrade of the Angular version has experienced poor performance of the application and it is sad that no one is looking into this.
    We have already tried other frameworks based on React, and they are doing great.

  11. imaksp commented on Aug 23, 2025

    @imaksp
    Contributor

    Hi, NG_BUILD_OPTIMIZE_CHUNKS option has reduced raw size of initial bundle significantly (from 3.16MB to 1.28MB) in one of our app, it is also reducing total number of chunks (from 143 to 138) but it still has so many lazy chunks . Hopefully new Rolldown experiment works and solves this issue related to esbuild and also the issue with dynamic import tree-shaking.

  12. ChristopherPHolder commented on Aug 30, 2025

    @ChristopherPHolder
    Author

    NG_BUILD_OPTIMIZE_CHUNKS option has reduced raw size of initial bundle significantly (from 3.16MB to 1.28MB)

    I highly doubt that, it not likely that you have a 3x reduction in bundle size. most likely there is an error in the computation of the new bundle cause it to ignore some of the bundles. How did you reach that conclusions?

  13. imaksp commented on Aug 30, 2025

    @imaksp
    Contributor

    NG_BUILD_OPTIMIZE_CHUNKS option has reduced raw size of initial bundle significantly (from 3.16MB to 1.28MB)

    I highly doubt that, it not likely that you have a 3x reduction in bundle size. most likely there is an error in the computation of the new bundle cause it to ignore some of the bundles. How did you reach that conclusions?

    Hi, I don't have before screenshot currently but result is consistent across 3 of our apps, it removes all chunks from initial bundle (keeps single main js file) and moves rest to lazy chunks, earlier initial bundle had many chunks (I think around 12 and around 115 lazy), this is build screenshot from one of our app (after adding this flag).

    Image
  14. jsaguet commented on Sep 4, 2025

    @jsaguet
    Contributor

    I'm having issues with the chunk optimizer since version 20.2.0. It seems to be much less effective now that rolldown is used instead of rollup.

    For example in my app, here is the number of generated js files per version (same application code)

    Version NG_BUILD_OPTIMIZE_CHUNKS=0 NG_BUILD_OPTIMIZE_CHUNKS=1
    20.1 (rollup) 448 241
    20.2 (rolldown) 449 442

    Has anyone else experienced the same thing ?

  15. phpbg commented on Sep 9, 2025

    @phpbg

    Same here: lots on <1kb chunks.
    After some investigation, they seems to contains, for example:

    • one single pipe
    • one single service
    • one single enum
    • one single directive

    This is a bit too much I think (at least for a single enum).

    Image
  16. phpbg commented on Sep 10, 2025

    @phpbg

    Previous similar issues were closed as won't fix:

    I am not sure if HTTP/2+ mitigates the high number of chunks. Indeed very small chunks defeats compression, so the whole transfer size may be higher.

    I don't know very well rollup/rolldown, but there are flags to set a minimum chunk size, which would solve the issue I guess. It would be nice to allow such a configuration flag in angular.json: rolldown/rolldown#4932

  17. phpbg commented on Sep 10, 2025

    @phpbg

    Here are quick metrics from the same environment.
    Note that due to internal enterprise constraints files are served over HTTP1.1.

    Before

    Image Image

    After

    Image Image

    Results

    • 10x requests
    • degraded transfer size
    • 2x DomContentLoaded event time
    • 5x load event time
    • LCP degradation
    • FCP slightly improved
    • From a (subjective) user perspective: slower loading time
  18. al0xf commented on Sep 15, 2025

    @al0xf

    You can see where the upgrade happened here on our Fastly dashboard showing total requests per day. Never mind any performance impact, there is also an impact on our bills...

    Image
  19. phpbg commented on Sep 15, 2025

    @phpbg

    @alan-agius4 do you still need more info (tag "needs: more info")?

  20. PowerKiKi commented on Sep 24, 2025

    @PowerKiKi
    Contributor

    Could the Angular team clarify why NG_BUILD_OPTIMIZE_CHUNKS is still experimental (according to the recent #30765) ? what would be required before it becomes stable ? and whether there is a possibility that this might be the default behavior in the (far?) future ?

    Also, out of curiosity, why is this implemented as env var, and not as an angular.json option ? and why all env vars seems to be entirely undocumented ? Grepping the source code I find ~60 things that might be env var and that might or might not be part of the public API... How are we supposed to discover those and know whether there are part of a public, stable, API ?

  21. imaksp commented on Sep 24, 2025

    @imaksp
    Contributor

    Hi, it might be because Rolldown is still in beta, but as per my testing it just removes chunks from initial bundle, it does not reduce total chunks (including lazy) by much.

  22. imaksp commented on Oct 3, 2025

    @imaksp
    Contributor

    Some updated stats from one of our app (@angular/build version 20.3.4):

    Without rolldown optimization (default):
    Total chunks count: 135
    Initial total: 3.38 MB

    With NG_BUILD_OPTIMIZE_CHUNKS:
    Total chunks count: 99 (so its working now but it still has many <1kB and <2kb chunks)
    Initial total: 3.46 MB (no chunks in initial bundle - all 99 are lazy but main bundle size has increased)

  23. ChristopherPHolder commented on Oct 13, 2025

    @ChristopherPHolder
    Author

    I figure it would be worth adding this:

    This is the impact of adding chunks.

    Basically i rendered an app and each route displays basically the same content but the content is split by being referenced in dynamic entries

    Image
    Extra Chunks LCP TEST Results
    STUB 1.611 250911_YiDcVG_5NC
    0 2.951 250911_YiDcRH_5NZ
    20 3.241 250911_YiDcNG_5NN
    100 3.568 250911_YiDcSB_5NY
    250 4.370 250911_YiDcVG_5N
    500 5.788 250911_YiDcAP_5NJ
  24. Azbesciak commented on Nov 5, 2025

    @Azbesciak

    Is there any ETA to completely address that issue?
    That does not look appealing, not to mention migrations are said to be seamless and rather improve the performance (as the whole esbuild migration was promising), whereas we have basic, rather not expected issues.

  25. sefatanam commented on Nov 27, 2025

    @sefatanam

    chunk after chunk, the horrible thing for me is now I can't see the imitator name from chrome devtool(network tab) instead showing chunks_ASDF, does anyone know how to get rid of it ?

    Image
  26. imaksp commented on Jun 26, 2026

    @imaksp
    Contributor

    It seems ESBuild has issues with tree shaking too, it can't tree shake modern viem lib properly, so as a workaround we need to pull some of its sub-dependencies directly.
    only 4 functions isAddress, formatUnits, getAddress, isAddressEqual were pulling ~200kB raw in our initial bundle. barrel import did not fix it either (from Claude: the viem/utils barrel drags in constants/abis, constants/contracts, errors/{rpc,abi,contract,transaction}, actions/public/call, parseTransaction, @noble/curves signing (secp256k1/weierstrass), and abitype)

    Also it seems NG_BUILD_CHUNKS_ROLLDOWN=1 has a reporting error, if we turn this on it significantly reduces Initial bundle size in build report , but actual diff was ~1% (for gzipped version)

  27. delagen commented on Jul 16, 2026

    @delagen

    Was ~1600 files, with NG_BUILD_CHUNKS_ROLLDOWN=1 now ~2400. Good optimization ;)

  28. eggsys commented on Sep 7, 2026

    @eggsys

    is this issue got solve by upgrading Angular version ?

  29. ChristopherPHolder commented on Sep 7, 2026

    @ChristopherPHolder
    Author

    is this issue got solve by upgrading Angular version ?

    I dont think this is something that will get "fixed" as its not really a regression or a bug but a core decition in the bundler.

    I wrote an article about it in case you want to read more about it https://push-based.io/article/faster-builds-slower-applications-optimizing-angulars-bundle-output

    Also we opensourced an experimental optimization that in most cases should work better then the default optimizer used in case someone wants to try it out we are open to feedback https://www.rx-angular.io/docs/packages/rebundle

  30. delagen commented on Oct 13, 2026

    @delagen

    @ChristopherPHolder I tried RxAngular/rebundle, it simply hangs forever in default configuration

  31. ChristopherPHolder commented on Oct 15, 2026

    @ChristopherPHolder
    Author

    28. @ChristopherPHolder I tried RxAngular/rebundle, it simply hangs forever in default configuration

    Can you provided some additional details about your project and how its configured?

    Also an issue with a reproducible would be appreciated @delagen

    https://github.com/rx-angular/rx-angular/issues

  32. delagen commented on Oct 15, 2026

    @delagen

    @ChristopherPHolder it's enterprise project, so i cannot share.

    Details that i can provide:
    Plugin added via @angular-builders/custom-esbuild with default config to angular-cli angular.json
    Actual angular 22 project

  33. softhouse2341 commented on Oct 22, 2026

    @softhouse2341

    This is worst design decision yet. And it looks like Angular team don't care because this issue is there for many angular versions. Also it looks like NG_BUILD_OPTIMIZE_CHUNKS changes hashes in too many chunks

  34. ChristopherPHolder commented on Oct 23, 2026

    @ChristopherPHolder
    Author

    30. @ChristopherPHolder it's enterprise project, so i cannot share.
    Details that i can provide:
    Plugin added via @angular-builders/custom-esbuild with default config to angular-cli angular.json
    Actual angular 22 project

    If there is anyway you can provide a reproducible we would be happy to fix you issue

    i can also integrate more debugging tools into it so we can find why its not functioning for you @delagen

  35. ChristopherPHolder commented on Oct 23, 2026

    @ChristopherPHolder
    Author

    I see more improvements related to the initial static closure are landing #34408 (comment)

    @clydin do you plan to implement this feature for internal static closures from a dynamic route? The PR you merged only seems to deal with the top layer which for apps that follow a shell pattern is simply not enough.

  36. imaksp commented on Oct 26, 2026

    @imaksp
    Contributor

    I see more improvements related to the initial static closure are landing #34408 (comment)

    @clydin do you plan to implement this feature for internal static closures from a dynamic route? The PR you merged only seems to deal with the top layer which for apps that follow a shell pattern is simply not enough.

    It seems that PR is just a fix for rollup version parity not a new improvement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions