Skip to content

Commit 20e86ee

Browse files
committed
feat(@angular/build): poc - shrink @defer chunks that pull in whole libraries
This is a prototype, not a finished fix. Nothing here is meant to be merged as-is. The problem: if you use @defer with a component from an npm package, Angular can end up putting the WHOLE package into your app's deferred chunk, even if you only use one small part of it. That makes your app bigger than it needs to be. Why it happens: Angular writes code like this for defer blocks: import("some-lib").then(m => m.MyThing) The import() part always loads the ENTIRE package. There's no way to ask it for just one piece. So the bundler (esbuild) can't remove the parts you're not using, because it can't be sure nothing else needs them. What this branch tries: a small esbuild plugin that spots this pattern and swaps it for a plain export line instead: export { MyThing } from 'some-lib'; That's just a normal export. esbuild CAN remove the unused parts of the package once it sees that. Does it actually work? Yes, but how much it helps depends a lot on the package: - Best case (a package made of fully separate pieces): about 88% smaller in a test. - Real test with ngx-markdown: only about 1.5% smaller, because most of what MarkdownComponent needs turned out to be stuff it can't avoid anyway. - Found a real bug while testing: for old-style CommonJS packages (tried it with lodash), this trick does not help at all, and was actually making the output a little bigger. Added a check so those packages get skipped now instead. What's tested: unit tests for the pattern matching, the rewrite step, and the esbuild plugin itself. 25 tests, all passing. What's still missing, on purpose: - Only wired into the browser build, not the server/SSR build. - Sourcemaps are not fully wired end to end yet. - Not tested against real incremental/watch-mode rebuilds. - Biggest open question: this works by guessing based on what the compiler's output looks like today. It would be safer if the compiler team could give us something more solid to look for instead of guessing. See the draft write-up for more on this. Full write-up: defer-dependency-tree-shaking.pr-draft.md
1 parent ecbcd87 commit 20e86ee

10 files changed

Lines changed: 860 additions & 0 deletions
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
<!--
2+
This is a draft PR description, kept as a plain file rather than opened as
3+
a real PR. Nothing on this branch is committed. Read this together with
4+
the diff before deciding whether to open it for real.
5+
-->
6+
7+
# [DRAFT / RFC] Stop `@defer` from pulling in whole third-party libraries
8+
9+
**Status: proof of concept, not ready to merge. Opening this mainly to ask the compiler team one question (see the bottom).**
10+
11+
## The problem, in one example
12+
13+
Say a component only shows up inside an `@defer` block, and it comes from a library:
14+
15+
```ts
16+
import { MarkdownComponent } from 'ngx-markdown';
17+
18+
@Component({
19+
imports: [MarkdownComponent],
20+
template: `@defer (on viewport) { <markdown [data]="text" /> }`,
21+
})
22+
```
23+
24+
You'd expect the deferred chunk to contain `MarkdownComponent` and whatever it actually needs. Instead, it contains the _entire_ `ngx-markdown` package - every component, every pipe, the clipboard button, the KaTeX and Mermaid integration, all of it - even though nothing else in your app ever references those.
25+
26+
## Why: `import()` can't ask for one export
27+
28+
The compiler turns that defer block into something like this:
29+
30+
```js
31+
import('ngx-markdown').then((m) => m.MarkdownComponent);
32+
```
33+
34+
That's not a bug in the codegen - it's just what `import()` does. It's a JS operator, not syntax with a "give me just this one export" mode. It always resolves to the whole module's namespace object. So `m` is the entire `ngx-markdown` module, and nothing downstream can prove that `m.MarkdownComponent` is the only thing anyone ever reads off it. A bundler can't tree-shake what it can't prove is unused, so the rest of the package rides along.
35+
36+
Compare that to a plain static import - `import { MarkdownComponent } from 'ngx-markdown'` - which tells the bundler exactly which binding is used, and lets it drop the rest.
37+
38+
## Why this lives in `@angular/build`, not the compiler
39+
40+
The compiler's job is to emit code that works everywhere Angular runs - esbuild, ng-packagr, JIT in a browser, whatever. It can't bake in "assume esbuild and rewrite the import" because that would break every other consumer of that same output. This is a decision about the _bundled_ result, and the bundler is the only place that gets to make it.
41+
42+
## What this branch does
43+
44+
An esbuild plugin that:
45+
46+
1. Recognizes the shape the compiler emits (`import(specifier).then(m => m.Symbol)`, with a `@ts-ignore` comment the compiler happens to put right above it).
47+
2. Rewrites it to import from a synthetic virtual module instead:
48+
```js
49+
import('angular:defer-dep:ngx-markdown:MarkdownComponent').then((m) => m.MarkdownComponent);
50+
```
51+
3. That virtual module's content is just:
52+
```js
53+
export { MarkdownComponent } from 'ngx-markdown';
54+
```
55+
56+
A static named re-export, unlike a dynamic `import()`, gives esbuild the information it needs to tree-shake the rest of the package. esbuild does the actual work here - this plugin's only job is getting a static re-export in front of it.
57+
58+
Where it lives:
59+
60+
- `defer-dependency-detector.ts` - just the pattern-matching, isolated on purpose (see the open question below).
61+
- `defer-dependency-rewriter.ts` - does the rewrite via `magic-string` (so it produces a real sourcemap), plus a guard that skips CommonJS packages (more on that below).
62+
- `defer-dependency-plugin.ts` - the esbuild plugin, built on the existing `createVirtualModulePlugin` helper.
63+
- One new line in `compiler-plugin.ts`, right before the compiled output gets cached, calling the rewriter.
64+
65+
## Does it actually work? Numbers, not vibes
66+
67+
**The ceiling - a library with genuinely independent exports (synthetic test, 8 unrelated classes, only 1 used):**
68+
69+
11,988 bytes → 1,397 bytes. **88% smaller.**
70+
71+
This is the case the bug report describes, and in that case the fix does exactly what you'd hope.
72+
73+
**The real-world case - `ngx-markdown`, deferring `MarkdownComponent`:**
74+
75+
59,804 bytes → 58,883 bytes. **1.5% smaller.**
76+
77+
Much less exciting, and worth being upfront about why: `MarkdownComponent` depends on `MarkdownService`, and `MarkdownService` isn't a small, separate thing you could theoretically shake away - it's one big file that already contains the KaTeX/Mermaid/clipboard option-handling code inline, because that's how the package author wrote it. Tree-shaking _does_ correctly drop the genuinely-unrelated stuff (`ClipboardButtonComponent`, `PrismPlugin`, `MarkdownModule` - confirmed these disappear from the output), but that's a small slice of the total file. Most of the weight was never avoidable for this component, fix or no fix.
78+
79+
Takeaway: this fix is real and it works, but how much it helps depends entirely on how a given library is structured. It'll do a lot for a component kit made of genuinely separate pieces, and not much for a library where the deferred symbol's own dependency chain already accounts for most of the bytes. `ngx-markdown` happened to be the example in the original bug report, and it's honestly not the best showcase for this - worth finding or building a better one before this goes further.
80+
81+
**A regression we found and fixed - CommonJS packages:**
82+
83+
Tested against `lodash` (`import("lodash").then(m => m.debounce)`). Before this fix: 73,060 bytes. First version of this fix: 73,598 bytes - _bigger_, not smaller. Turns out esbuild bundles a CommonJS module as one opaque object no matter which property you read off it afterwards, so rerouting through a static re-export doesn't unlock any tree-shaking there - it just adds an extra layer of indirection for nothing. Confirmed with a grep: both bundles contained lodash's entire export list, `debounce` or not.
84+
85+
Fixed by checking the target package's `package.json` (`type: "module"`, a `module` field, or an `import` condition in `exports`) before rewriting anything, and leaving CommonJS packages alone entirely. Re-tested after the fix: 73,060 → 73,060 bytes, no change either way. This guard is why `defer-dependency-rewriter.ts` exists as a separate step from the plugin - it's a decision that has to happen before the rewrite, not inside esbuild's module resolution.
86+
87+
**Default exports** work too - tested against a real package (`clsx`) by actually running the built output before and after the rewrite and confirming it computes the same result, plus a synthetic test (default export + 7 independent siblings) showing the same ~89% reduction as the named-export case.
88+
89+
**Sourcemaps** - the rewrite runs through `magic-string`, and tracing real esbuild output back through the generated map confirms surrounding code (the untouched half of the `.then()` call) still points at the correct original line. One real gap: this rewrite's own sourcemap isn't merged into the one `javascriptTransformer.transformData` produces right after it in `compiler-plugin.ts` - fine for this PoC since the rewrite is a same-line string swap, not something to leave unresolved before merging.
90+
91+
## What's explicitly not done here
92+
93+
- Only wired into the main browser bundle, not the server/SSR bundle path.
94+
- No caching/watch-mode testing beyond reading the code and finding the right integration point (right before `typeScriptFileCache.set()`, so a cache hit returns already-rewritten content for free - untested against a real incremental rebuild).
95+
- Sourcemap chaining into `javascriptTransformer.transformData`'s own remapping, as mentioned above.
96+
- Only checked against ESM and CommonJS interop shapes, not every possible export style (re-exports under a different upstream name, e.g. `export { Foo as Bar }`, weren't tested - though the compiler always uses the name from the user's own `import` statement, so this should be transparent, just unverified).
97+
98+
## The actual question for the compiler team
99+
100+
The detection here is pattern-matching against `@angular/compiler`'s current output shape - specifically, an `import().then(param => param.prop)` call with a `@ts-ignore` comment sitting right above it. That comment is a real signal today (the compiler doesn't use `@ts-ignore` on that exact shape anywhere else), but it's an implementation detail of the printer, not a contract anyone promised to keep stable. It also happens to be the same comment the compiler uses for a few unrelated things elsewhere in the file, which is a little too close for comfort.
101+
102+
**Would it be reasonable to ask for a small, dedicated marker on defer-dependency imports specifically** - a distinct comment, or something else identifiable - so a bundler doesn't have to reverse-engineer "is this a defer dependency" from what the printer happens to currently produce? The detection logic is isolated into its own file (`defer-dependency-detector.ts`) specifically so that swapping "sniff the current shape" for "read an explicit marker" would be a contained change, not a rewrite of the rewriter or the plugin.
103+
104+
This PR is as much about surfacing that question as it is about the plugin itself.

‎packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import { LoadResultCache, createCachedLoad } from '../load-result-cache';
3030
import { logCumulativeDurations, profileAsync, resetCumulativeDurations } from '../profiling';
3131
import { AngularCompilationContext } from './compilation-state';
3232
import { ComponentStylesheetBundler } from './component-stylesheets';
33+
import { isEsmPackage, rewriteDeferDependencyImports } from './defer-dependency-rewriter';
3334
import { FileReferenceTracker } from './file-reference-tracker';
3435
import { setupJitPluginCallbacks } from './jit-plugin-callbacks';
3536
import { rewriteForBazel } from './rewrite-bazel-paths';
@@ -499,6 +500,29 @@ export function createCompilerPlugin(
499500
} else if (typeof contents === 'string' && (useTypeScriptTranspilation || isJS)) {
500501
// A string indicates untransformed output from the TS/NG compiler.
501502
// This step is unneeded when using esbuild transpilation.
503+
504+
// PoC: if this file has a `@defer`-generated import like
505+
// `import('some-lib').then(m => m.SomeComponent)`, rewrite it so
506+
// esbuild can drop the rest of `some-lib` from the deferred
507+
// chunk. See defer-dependency-rewriter.ts for the details and
508+
// what's still missing.
509+
//
510+
// We do this right here, before the cache write below, so that
511+
// on the next incremental build, a cache hit already has the
512+
// rewritten code and doesn't need to redo any of this work.
513+
//
514+
// Known gap: we don't merge our source map with the one
515+
// `javascriptTransformer.transformData` creates right below.
516+
// That's fine for a proof of concept - we're only swapping out a
517+
// string here, nothing actually moves around - but it would need
518+
// fixing before this could really be merged.
519+
const rewritten = rewriteDeferDependencyImports(contents, request, (specifier) =>
520+
isEsmPackage(specifier, path.dirname(request)),
521+
);
522+
if (rewritten) {
523+
contents = rewritten.code;
524+
}
525+
502526
const sideEffects = await hasSideEffects(request);
503527
const instrumentForCoverage = pluginOptions.instrumentForCoverage?.(request);
504528
contents = await javascriptTransformer.transformData(
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import ts from 'typescript';
10+
11+
/**
12+
* A single `@defer`-generated dependency import found in a file, e.g. the
13+
* `import("some-lib").then(m => m.SomeComponent)` inside a defer block's
14+
* resolver function.
15+
*/
16+
export interface DeferDependencyImportMatch {
17+
/** Start offset of the import()'s argument list, e.g. right after `import(`. */
18+
start: number;
19+
20+
/** End offset of the import()'s argument list, e.g. right before `)`. */
21+
end: number;
22+
23+
/** The module specifier as written by the user, e.g. `'some-lib'`. */
24+
specifier: string;
25+
26+
/** The exported symbol being read off the resolved module, e.g. `SomeComponent` or `default`. */
27+
symbol: string;
28+
}
29+
30+
/**
31+
* Looks for `@defer`-generated dependency imports in a file - the code
32+
* Angular writes when a component is only used inside a `@defer` block,
33+
* which looks like this:
34+
*
35+
* import("some-lib").then(m => m.SomeComponent)
36+
*
37+
* This is just pattern matching against what `@angular/compiler` happens
38+
* to produce today (see `compileDeferResolverFunction` if you want to look
39+
* at the source). The compiler has never promised this exact shape will
40+
* stay the same, so this logic is kept in its own file on purpose: if the
41+
* compiler team ever gives us something more reliable to look for (a real
42+
* marker, say), we should only need to change this one file.
43+
*
44+
* Why we think this match is safe enough to use:
45+
* - It's rare for hand-written code to look like this. The closest
46+
* real-world example is a Router `loadComponent`/`loadChildren` route,
47+
* but those almost always use a relative path like `./foo`, so we skip
48+
* anything that isn't a plain package name.
49+
* - We also require a `@ts-ignore` comment right above the import. The
50+
* compiler does use `@ts-ignore` in a few unrelated places too, but
51+
* never on this exact shape - so requiring both the shape *and* the
52+
* comment together is a pretty strong signal.
53+
*
54+
* Still, this is a guess, not a guarantee. See the PR description for the
55+
* question we're asking the compiler team about this.
56+
*/
57+
export function findDeferDependencyImports(
58+
code: string,
59+
fileName: string,
60+
): DeferDependencyImportMatch[] {
61+
const sourceFile = ts.createSourceFile(
62+
fileName,
63+
code,
64+
ts.ScriptTarget.ES2022,
65+
/* setParentNodes */ true,
66+
ts.ScriptKind.JS,
67+
);
68+
69+
const matches: DeferDependencyImportMatch[] = [];
70+
71+
// TypeScript actually has a built-in helper for this, `ts.isImportCall`,
72+
// but it's not part of the public types for the TypeScript version this
73+
// repo uses right now. So we just check the node type by hand instead.
74+
function isDynamicImportCall(node: ts.CallExpression): boolean {
75+
return node.expression.kind === ts.SyntaxKind.ImportKeyword;
76+
}
77+
78+
function hasNearbyTsIgnore(node: ts.Node): boolean {
79+
// Angular writes the comment like this:
80+
//
81+
// [/* @ts-ignore */
82+
// import(...)]
83+
//
84+
// Notice the comment is on the same line as the `[` before it, not on
85+
// its own line right above the import. Because of that, TypeScript
86+
// doesn't count it as "belonging to" the import - so the normal way of
87+
// checking for a leading comment (`ts.getLeadingCommentRanges`) misses
88+
// it here. Just checking the raw text in between is simpler and works
89+
// no matter how the comment is attached.
90+
return code.slice(node.pos, node.getStart(sourceFile)).includes('@ts-ignore');
91+
}
92+
93+
function visit(node: ts.Node): void {
94+
if (
95+
ts.isCallExpression(node) &&
96+
ts.isPropertyAccessExpression(node.expression) &&
97+
node.expression.name.text === 'then' &&
98+
ts.isCallExpression(node.expression.expression) &&
99+
isDynamicImportCall(node.expression.expression) &&
100+
node.arguments.length === 1
101+
) {
102+
const importCall = node.expression.expression;
103+
const specifierArg = importCall.arguments[0];
104+
const thenArg = node.arguments[0];
105+
106+
const isSimplePropertyAccessCallback =
107+
(ts.isArrowFunction(thenArg) || ts.isFunctionExpression(thenArg)) &&
108+
thenArg.parameters.length === 1 &&
109+
ts.isIdentifier(thenArg.parameters[0].name) &&
110+
!!thenArg.body &&
111+
ts.isPropertyAccessExpression(thenArg.body) &&
112+
ts.isIdentifier(thenArg.body.expression) &&
113+
thenArg.body.expression.text === thenArg.parameters[0].name.text;
114+
115+
if (
116+
specifierArg &&
117+
ts.isStringLiteralLike(specifierArg) &&
118+
isSimplePropertyAccessCallback &&
119+
hasNearbyTsIgnore(node)
120+
) {
121+
const specifier = specifierArg.text;
122+
123+
// Skip relative paths like './foo' - that's almost certainly a
124+
// Router route someone wrote by hand, not something the compiler
125+
// generated. It's also not a case we need to fix: a relative
126+
// import points at your own file, not at an unrelated package, so
127+
// there's no "whole library got pulled in" problem to solve.
128+
if (!specifier.startsWith('.') && !specifier.startsWith('/')) {
129+
matches.push({
130+
start: importCall.arguments.pos,
131+
end: importCall.arguments.end,
132+
specifier,
133+
symbol: (thenArg.body as ts.PropertyAccessExpression).name.text,
134+
});
135+
}
136+
}
137+
}
138+
139+
ts.forEachChild(node, visit);
140+
}
141+
142+
visit(sourceFile);
143+
144+
return matches;
145+
}

0 commit comments

Comments
 (0)