Skip to content

Commit 8ca1d0b

Browse files
fix(vite-plugin-angular): emit fastCompile providers referenced by a const (#2388)
1 parent 39fa344 commit 8ca1d0b

3 files changed

Lines changed: 112 additions & 21 deletions

File tree

‎packages/vite-plugin-angular/src/lib/compiler/compile.ts‎

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,27 @@ function hasExportModifier(node: ts.Node): boolean {
124124
);
125125
}
126126

127+
/**
128+
* Normalize a `providers` / `viewProviders` metadata value into the single
129+
* `o.Expression` Angular's injector/host emitters expect.
130+
*
131+
* `extractMetadata` stores these as an array of `WrappedNodeExpr` when the
132+
* source used an inline array literal (`providers: [A, B]`) — those get
133+
* wrapped in a `LiteralArrayExpr`. When the source referenced a const,
134+
* spread, or call instead (`providers: safeProviders`), it stores the raw
135+
* expression, which is emitted by value. Returns `null` when there is
136+
* nothing to emit so callers skip the feature entirely.
137+
*/
138+
function providersToExpr(
139+
value: o.Expression[] | o.Expression | undefined | null,
140+
): o.Expression | null {
141+
if (!value) return null;
142+
if (Array.isArray(value)) {
143+
return value.length ? new o.LiteralArrayExpr(value) : null;
144+
}
145+
return value;
146+
}
147+
127148
/**
128149
* Collect identifier names referenced in eagerly-evaluated code only.
129150
* Skips function/arrow/class bodies so that lazy references
@@ -728,12 +749,8 @@ export function compile(
728749
changeDetection: meta.changeDetection ?? (isPartial ? null : 1),
729750
encapsulation: meta.encapsulation ?? 0,
730751
exportAs: meta.exportAs,
731-
providers: meta.providers?.length
732-
? new o.LiteralArrayExpr(meta.providers)
733-
: null,
734-
viewProviders: meta.viewProviders?.length
735-
? new o.LiteralArrayExpr(meta.viewProviders)
736-
: null,
752+
providers: providersToExpr(meta.providers),
753+
viewProviders: providersToExpr(meta.viewProviders),
737754
animations: meta.animations?.length
738755
? new o.LiteralArrayExpr(meta.animations)
739756
: null,
@@ -885,16 +902,13 @@ export function compile(
885902
queries: [...fields.contentQueries, ...sigs.contentQueries],
886903
// Angular's compiler treats `providers` as an Expression and
887904
// emits `ɵɵProvidersFeature(<expr>)` whenever it is truthy.
888-
// Passing the bare JS array of WrappedNodeExpr from
889-
// extractMetadata causes the emitter to lower it to `null`,
890-
// which then crashes Angular at runtime in `resolveProvider`
891-
// because it tries to read `.provide` on `null`. Wrap into a
892-
// LiteralArrayExpr (matching the Component branch) so it
893-
// emits a real array literal — and pass `null` when there are
894-
// no providers so Angular skips the feature entirely.
895-
providers: meta.providers?.length
896-
? new o.LiteralArrayExpr(meta.providers)
897-
: null,
905+
// `providersToExpr` lowers an inline array literal to a
906+
// LiteralArrayExpr (matching the Component branch) and passes a
907+
// const/spread reference through by value — returning `null`
908+
// when there are no providers so Angular skips the feature
909+
// entirely. Passing the bare JS array would otherwise be lowered
910+
// to `null` and crash Angular at runtime in `resolveProvider`.
911+
providers: providersToExpr(meta.providers),
898912
exportAs: meta.exportAs,
899913
isStandalone: meta.standalone,
900914
lifecycle: { usesOnChanges: false },
@@ -1054,9 +1068,7 @@ export function compile(
10541068
const injectorMeta = {
10551069
name: className,
10561070
type: classRef,
1057-
providers: meta.providers
1058-
? new o.LiteralArrayExpr(meta.providers)
1059-
: null,
1071+
providers: providersToExpr(meta.providers),
10601072
imports: ngModuleImports.map((e: o.WrappedNodeExpr<any>) => e),
10611073
};
10621074
if (isPartial) {

‎packages/vite-plugin-angular/src/lib/compiler/metadata.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -284,8 +284,6 @@ export function extractMetadata(
284284
}
285285
break;
286286
case 'imports':
287-
case 'providers':
288-
case 'viewProviders':
289287
case 'animations':
290288
case 'rawImports':
291289
case 'declarations':
@@ -297,6 +295,28 @@ export function extractMetadata(
297295
);
298296
}
299297
break;
298+
case 'providers':
299+
case 'viewProviders':
300+
if (valNode.type === 'ArrayExpression') {
301+
meta[key] = (valNode.elements || []).map(
302+
(e: any) => new o.WrappedNodeExpr(unwrapForwardRefOxc(e)),
303+
);
304+
} else {
305+
// `providers: safeProviders` / `viewProviders: SHARED_PROVIDERS`
306+
// — a reference to a module-level const (or any non-literal
307+
// expression such as a spread or function call) rather than an
308+
// inline array literal. ngtsc's partial evaluator expands the
309+
// identifier to its array; fastCompile does no static evaluation,
310+
// so it cannot. But Angular emits injector/host `providers` as a
311+
// single Expression and flattens nested arrays at runtime, so the
312+
// reference can be passed through by value. Storing it as a bare
313+
// `o.Expression` (not an array) signals the emission sites to emit
314+
// it directly instead of wrapping it in a `LiteralArrayExpr`.
315+
// Without this, the whole `providers` list is silently dropped and
316+
// every token it provides fails at runtime with NG0201.
317+
meta[key] = new o.WrappedNodeExpr(valNode);
318+
}
319+
break;
300320
// @Injectable provider configuration. Pass these through to
301321
// compileInjectable so the emitted `ɵprov` reflects the user's
302322
// intent. `useClass`/`useExisting`/`useValue` are

‎packages/vite-plugin-angular/src/lib/compiler/ngmodule.spec.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,65 @@ describe('@NgModule', () => {
4949
expect(result).toContain('MyService');
5050
});
5151

52+
it('emits providers referenced by a const identifier instead of an inline array', () => {
53+
// `providers: <identifier>` (a module-level const array, common with
54+
// helpers like Bitwarden's `safeProvider(...)` collected into a
55+
// `safeProviders` const) must be passed through to `ɵɵdefineInjector`
56+
// by reference. fastCompile does no static evaluation, so it cannot
57+
// expand the identifier the way ngtsc does — but Angular flattens the
58+
// expression at runtime. Previously the non-array value was dropped,
59+
// emitting `ɵɵdefineInjector({})` and failing every provided token with
60+
// NG0201 at runtime.
61+
const result = compile(
62+
`
63+
import { NgModule, Injectable } from '@angular/core';
64+
65+
@Injectable()
66+
export class MyService {}
67+
68+
const providers = [MyService];
69+
70+
@NgModule({
71+
providers,
72+
})
73+
export class ServiceModule {}
74+
`,
75+
'ref-service.module.ts',
76+
);
77+
78+
expectCompiles(result);
79+
expect(result).toContain('ɵinj');
80+
// The injector definition must reference the const, not be emitted empty.
81+
expect(result).toMatch(/ɵɵdefineInjector\(\{\s*providers\b/);
82+
expect(result).not.toMatch(/ɵɵdefineInjector\(\{\s*\}\)/);
83+
});
84+
85+
it('emits component providers referenced by a const identifier', () => {
86+
const result = compile(
87+
`
88+
import { Component, Injectable } from '@angular/core';
89+
90+
@Injectable()
91+
export class PanelService {}
92+
93+
const PANEL_PROVIDERS = [PanelService];
94+
95+
@Component({
96+
selector: 'app-panel',
97+
template: '<span>panel</span>',
98+
providers: PANEL_PROVIDERS,
99+
})
100+
export class PanelComponent {}
101+
`,
102+
'panel.component.ts',
103+
);
104+
105+
expectCompiles(result);
106+
// ɵɵProvidersFeature must receive the referenced const, not null.
107+
expect(result).toContain('ɵɵProvidersFeature');
108+
expect(result).toContain('PANEL_PROVIDERS');
109+
});
110+
52111
it('resolves NgModule exports when imported by a component', () => {
53112
const childSrc = `
54113
import { Component } from '@angular/core';

0 commit comments

Comments
 (0)