-
-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathangular-vite-plugin.ts
More file actions
1890 lines (1686 loc) · 64 KB
/
Copy pathangular-vite-plugin.ts
File metadata and controls
1890 lines (1686 loc) · 64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { NgtscProgram } from '@angular/compiler-cli';
import { mkdirSync, writeFileSync, promises as fsPromises } from 'node:fs';
import {
basename,
dirname,
isAbsolute,
join,
relative,
resolve,
} from 'node:path';
import * as vite from 'vite';
import * as compilerCli from '@angular/compiler-cli';
import { createRequire } from 'node:module';
import * as ts from 'typescript';
import { type createAngularCompilation as createAngularCompilationType } from '@angular/build/private';
import * as ngCompiler from '@angular/compiler';
import { globSync } from 'tinyglobby';
import {
defaultClientConditions,
ModuleNode,
normalizePath,
Plugin,
preprocessCSS,
ResolvedConfig,
ViteDevServer,
} from 'vite';
import { buildOptimizerPlugin } from './angular-build-optimizer-plugin.js';
import { jitPlugin } from './angular-jit-plugin.js';
import {
StyleUrlsResolver,
TemplateUrlsResolver,
} from './component-resolvers.js';
import {
augmentHostWithCaching,
augmentHostWithResources,
augmentProgramWithVersioning,
mergeTransformers,
} from './host.js';
import { angularVitestPlugins } from './angular-vitest-plugin.js';
import {
createAngularCompilation,
createJitResourceTransformer,
SourceFileCache,
angularFullVersion,
} from './utils/devkit.js';
import { type SourceFileCache as SourceFileCacheType } from './utils/source-file-cache.js';
const require = createRequire(import.meta.url);
import { pendingTasksPlugin } from './angular-pending-tasks.plugin.js';
import { liveReloadPlugin } from './live-reload-plugin.js';
import { EmitFileResult } from './models.js';
import { nxFolderPlugin } from './nx-folder-plugin.js';
import {
FileReplacement,
FileReplacementSSR,
FileReplacementWith,
replaceFiles,
} from './plugins/file-replacements.plugin.js';
import { routerPlugin } from './router-plugin.js';
import { createHash } from 'node:crypto';
import { fastCompilePlugin } from './fast-compile-plugin.js';
import { oxcLinkerPlugin } from './compiler/oxc-linker-plugin.js';
import {
TS_EXT_REGEX,
createTsConfigGetter,
getTsConfigPath,
createDepOptimizerConfig,
type TsConfigResolutionContext,
} from './utils/plugin-config.js';
import { VIRTUAL_RAW_PREFIX, toVirtualRawId } from './utils/virtual-ids.js';
import {
loadVirtualRawModule,
rewriteHtmlRawImport,
} from './utils/virtual-resources.js';
import { markStylePathSafe } from './utils/safe-module-paths.js';
export enum DiagnosticModes {
None = 0,
Option = 1 << 0,
Syntactic = 1 << 1,
Semantic = 1 << 2,
All = Option | Syntactic | Semantic,
}
export interface PluginOptions {
tsconfig?: string | (() => string);
workspaceRoot?: string;
inlineStylesExtension?: string;
jit?: boolean;
advanced?: {
/**
* Custom TypeScript transformers that are run before Angular compilation
*/
tsTransformers?: ts.CustomTransformers;
};
supportedBrowsers?: string[];
transformFilter?: (code: string, id: string) => boolean;
/**
* Additional files to include in compilation
*/
include?: string[];
additionalContentDirs?: string[];
liveReload?: boolean;
disableTypeChecking?: boolean;
fileReplacements?: FileReplacement[];
/**
* Opt into the fast compile path and select the engine that backs it. The
* fast path skips Angular's template type-checking and routes compilation
* through an internal single-pass transform.
* - `false` (default) / unset: use Angular's full compilation (with
* template type-checking).
* - `true` or `'ts'`: the in-process TS/OXC-AST compiler shipped with this
* package.
* - `'oxc'`: experimental — route component compilation through the native
* Rust pipeline from `@oxc-angular/vite` (must be installed as an optional
* peer dependency).
*
* The OXC engine can also be selected with the `ANALOG_OXC=true` environment
* variable when this option is left unset (explicit values take precedence).
*/
fastCompile?: boolean | 'ts' | 'oxc';
/**
* Compilation output mode used when `fastCompile` is enabled.
* - `'full'` (default): Emit final Ivy definitions for application builds.
* - `'partial'`: Emit partial declarations for library publishing.
*/
fastCompileMode?: 'full' | 'partial';
experimental?: {
useAngularCompilationAPI?: boolean;
};
}
const classNames = new Map();
interface DeclarationFile {
declarationFileDir: string;
declarationPath: string;
data: string;
}
/**
* Subset of the esbuild-style `PartialMessage` that `@angular/build`'s
* `diagnoseFiles()` returns. Only the fields the plugin reads are modeled.
*/
export interface AngularDiagnostic {
text?: string;
location?: {
file?: string;
line?: number;
column?: number;
} | null;
}
export function angular(options?: PluginOptions): Plugin[] {
/**
* Normalize plugin options so defaults
* are used for values not provided.
*/
// Resolve the consolidated `fastCompile` option (boolean | 'ts' | 'oxc')
// into an internal enabled flag + engine. `ANALOG_OXC=true` selects the OXC
// engine when the option is unset; explicit config takes precedence.
const oxcEngineFromEnv = process.env['ANALOG_OXC'] === 'true';
const fastCompileValue =
options?.fastCompile ?? (oxcEngineFromEnv ? 'oxc' : false);
const fastCompileEngine: 'ts' | 'oxc' =
fastCompileValue === 'oxc' ? 'oxc' : 'ts';
const pluginOptions = {
tsconfigGetter: createTsConfigGetter(options?.tsconfig),
workspaceRoot: options?.workspaceRoot ?? process.cwd(),
inlineStylesExtension: options?.inlineStylesExtension ?? 'css',
advanced: {
tsTransformers: {
before: options?.advanced?.tsTransformers?.before ?? [],
after: options?.advanced?.tsTransformers?.after ?? [],
afterDeclarations:
options?.advanced?.tsTransformers?.afterDeclarations ?? [],
},
},
supportedBrowsers: options?.supportedBrowsers ?? ['safari 15'],
jit: options?.jit,
include: options?.include ?? [],
additionalContentDirs: options?.additionalContentDirs ?? [],
liveReload: options?.liveReload ?? false,
disableTypeChecking: options?.disableTypeChecking ?? true,
fileReplacements: options?.fileReplacements ?? [],
useAngularCompilationAPI:
options?.experimental?.useAngularCompilationAPI ?? false,
fastCompile: fastCompileValue !== false,
fastCompileMode: options?.fastCompileMode ?? 'full',
fastCompileEngine,
};
let resolvedConfig: ResolvedConfig;
let tsConfigResolutionContext: TsConfigResolutionContext | null = null;
const ts = require('typescript');
let builder: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram;
let nextProgram: NgtscProgram | undefined;
// Caches (always rebuild Angular program per user request)
const tsconfigOptionsCache = new Map<
string,
{ options: ts.CompilerOptions; rootNames: string[] }
>();
let cachedHost: ts.CompilerHost | undefined;
let cachedHostKey: string | undefined;
let includeCache: string[] = [];
function invalidateFsCaches() {
includeCache = [];
}
function invalidateTsconfigCaches() {
// `readConfiguration` caches the root file list, so hot-added pages can be
// missing from Angular's compilation program until we clear this state.
tsconfigOptionsCache.clear();
cachedHost = undefined;
cachedHostKey = undefined;
}
let watchMode = false;
let testWatchMode = isTestWatchMode();
let inlineComponentStyles: Map<string, string> | undefined;
let externalComponentStyles: Map<string, string> | undefined;
const sourceFileCache: SourceFileCacheType = new SourceFileCache();
const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];
const isVitestVscode = !!process.env['VITEST_VSCODE'];
const isStackBlitz = !!process.versions['webcontainer'];
const isAstroIntegration = process.env['ANALOG_ASTRO'] === 'true';
const jit =
typeof pluginOptions?.jit !== 'undefined' ? pluginOptions.jit : isTest;
let viteServer: ViteDevServer | undefined;
const styleUrlsResolver = new StyleUrlsResolver();
const templateUrlsResolver = new TemplateUrlsResolver();
let outputFile: ((file: string) => void) | undefined;
const outputFiles = new Map<string, EmitFileResult>();
const fileEmitter = (file: string) => {
outputFile?.(file);
return outputFiles.get(normalizePath(file));
};
let initialCompilation = false;
const declarationFiles: DeclarationFile[] = [];
const fileTransformMap = new Map<string, string>();
let styleTransform: (
code: string,
filename: string,
) => Promise<vite.PreprocessCSSResult>;
let pendingCompilation: Promise<void> | null;
let compilationLock = Promise.resolve();
// Persistent Angular Compilation API instance. Kept alive across rebuilds so
// Angular can diff previous state and emit `templateUpdates` for HMR.
// Previously the compilation was recreated on every pass, which meant Angular
// never had prior state and could never produce HMR payloads.
let angularCompilation:
| Awaited<ReturnType<typeof createAngularCompilationType>>
| undefined;
function angularPlugin(): Plugin {
let isProd = false;
if (angularFullVersion < 190000 || isTest) {
pluginOptions.liveReload = false;
}
// liveReload and fileReplacements guards were previously here and forced
// both options off when useAngularCompilationAPI was enabled. Those guards
// have been removed because:
// - liveReload: the persistent compilation instance (above) now gives
// Angular the prior state it needs to emit `templateUpdates` for HMR
// - fileReplacements: Angular's AngularHostOptions already accepts a
// `fileReplacements` record — we now convert and pass it through in
// `performAngularCompilation` via `toAngularCompilationFileReplacements`
if (pluginOptions.useAngularCompilationAPI) {
if (angularFullVersion < 200100) {
pluginOptions.useAngularCompilationAPI = false;
console.warn(
'[@analogjs/vite-plugin-angular]: The Angular Compilation API is only available with Angular v20.1 and later',
);
}
}
return {
name: '@analogjs/vite-plugin-angular',
async config(config, { command }) {
watchMode = command === 'serve';
isProd =
config.mode === 'production' ||
process.env['NODE_ENV'] === 'production';
// Store the config context for later resolution in configResolved
tsConfigResolutionContext = {
root: config.root || '.',
isProd,
isLib: !!config?.build?.lib,
};
// Do a preliminary resolution for esbuild plugin (before configResolved)
const preliminaryTsConfigPath = resolveTsConfigPath();
const esbuild = pluginOptions.useAngularCompilationAPI
? undefined
: (config.esbuild ?? false);
const oxc = pluginOptions.useAngularCompilationAPI
? undefined
: (config.oxc ?? false);
const depOptimizer = createDepOptimizerConfig({
tsconfig: preliminaryTsConfigPath,
isProd,
jit,
watchMode,
isTest,
isAstroIntegration,
});
return {
...(vite.rolldownVersion ? { oxc } : { esbuild }),
...depOptimizer,
resolve: {
conditions: [
...depOptimizer.resolve.conditions,
...(config.resolve?.conditions || defaultClientConditions),
],
},
};
},
configResolved(config) {
resolvedConfig = config;
if (pluginOptions.useAngularCompilationAPI) {
externalComponentStyles = new Map();
inlineComponentStyles = new Map();
}
if (!jit) {
styleTransform = (code: string, filename: string) =>
preprocessCSS(code, filename, config);
}
if (isTest) {
// set test watch mode
// - vite override from vitest-angular
// - @nx/vite executor set server.watch explicitly to undefined (watch)/null (watch=false)
// - vite config for test.watch variable
// - vitest watch mode detected from the command line
testWatchMode =
!(config.server.watch === null) ||
(config as any).test?.watch === true ||
testWatchMode;
}
},
configureServer(server) {
viteServer = server;
// Add/unlink changes the TypeScript program shape, not just file
// contents, so we need to invalidate both include discovery and the
// cached tsconfig root names before recompiling.
const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(
invalidateFsCaches,
invalidateTsconfigCaches,
() => performCompilation(resolvedConfig),
);
server.watcher.on('add', invalidateCompilationOnFsChange);
server.watcher.on('unlink', invalidateCompilationOnFsChange);
server.watcher.on('change', (file) => {
if (file.includes('tsconfig')) {
invalidateTsconfigCaches();
}
});
},
async buildStart() {
// Defer the first compilation in test mode
if (!isVitestVscode) {
await performCompilation(resolvedConfig);
pendingCompilation = null;
initialCompilation = true;
}
},
buildEnd() {
// Report diagnostics for production builds. Watch/serve already report
// per-module from `transform`; build mode defers to here so a single
// errored file no longer aborts the build before the rest are checked
// — every file's diagnostics are aggregated and reported together.
// Which diagnostics exist is governed by `disableTypeChecking` inside
// `getDiagnosticsForSourceFile` (syntactic-only by default, full
// semantic + Angular template diagnostics when type checking is on),
// so reporting itself is unconditional.
if (watchMode) {
return;
}
const { errors, warnings } = collectEmittedDiagnostics(outputFiles);
if (warnings.length > 0) {
this.warn(warnings.join('\n'));
}
if (errors.length > 0) {
this.error(errors.join('\n\n'));
}
},
async handleHotUpdate(ctx) {
if (TS_EXT_REGEX.test(ctx.file)) {
let [fileId] = ctx.file.split('?');
pendingCompilation = performCompilation(resolvedConfig, [fileId]);
let result;
if (pluginOptions.liveReload) {
await pendingCompilation;
pendingCompilation = null;
result = fileEmitter(fileId);
}
if (
pluginOptions.liveReload &&
result?.hmrEligible &&
classNames.get(fileId)
) {
const relativeFileId = `${normalizePath(
relative(process.cwd(), fileId),
)}@${classNames.get(fileId)}`;
sendHMRComponentUpdate(ctx.server, relativeFileId);
return ctx.modules.map((mod) => {
if (mod.id === ctx.file) {
return markModuleSelfAccepting(mod);
}
return mod;
});
}
}
if (/\.(html|htm|css|less|sass|scss)$/.test(ctx.file)) {
fileTransformMap.delete(ctx.file.split('?')[0]);
/**
* Check to see if this was a direct request
* for an external resource (styles, html).
*/
const isDirect = ctx.modules.find(
(mod) => ctx.file === mod.file && mod.id?.includes('?direct'),
);
const isInline = ctx.modules.find(
(mod) => ctx.file === mod.file && mod.id?.includes('?inline'),
);
if (isDirect || isInline) {
if (pluginOptions.liveReload && isDirect?.id && isDirect.file) {
const isComponentStyle =
isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);
if (isComponentStyle) {
const { encapsulation } = getComponentStyleSheetMeta(
isDirect.id,
);
// Track if the component uses ShadowDOM encapsulation
// Shadow DOM components currently require a full reload.
// Vite's CSS hot replacement does not support shadow root searching.
if (encapsulation !== 'shadow') {
ctx.server.ws.send({
type: 'update',
updates: [
{
type: 'css-update',
timestamp: Date.now(),
path: isDirect.url,
acceptedPath: isDirect.file,
},
],
});
return ctx.modules
.filter((mod) => {
// Component stylesheets will have 2 modules (*.component.scss and *.component.scss?direct&ngcomp=xyz&e=x)
// We remove the module with the query params to prevent vite double logging the stylesheet name "hmr update *.component.scss, *.component.scss?direct&ngcomp=xyz&e=x"
return mod.file !== ctx.file || mod.id !== isDirect.id;
})
.map((mod) => {
if (mod.file === ctx.file) {
return markModuleSelfAccepting(mod);
}
return mod;
}) as ModuleNode[];
}
}
}
return ctx.modules;
}
const mods: ModuleNode[] = [];
const updates: string[] = [];
ctx.modules.forEach((mod) => {
mod.importers.forEach((imp) => {
ctx.server.moduleGraph.invalidateModule(imp);
if (pluginOptions.liveReload && classNames.get(imp.id)) {
updates.push(imp.id as string);
} else {
mods.push(imp);
}
});
});
pendingCompilation = performCompilation(resolvedConfig, [
...mods.map((mod) => mod.id as string),
...updates,
]);
if (updates.length > 0) {
await pendingCompilation;
pendingCompilation = null;
updates.forEach((updateId) => {
const impRelativeFileId = `${normalizePath(
relative(process.cwd(), updateId),
)}@${classNames.get(updateId)}`;
sendHMRComponentUpdate(ctx.server, impRelativeFileId);
});
return ctx.modules.map((mod) => {
if (mod.id === ctx.file) {
return markModuleSelfAccepting(mod);
}
return mod;
});
}
return mods;
}
// clear HMR updates with a full reload
classNames.clear();
return ctx.modules;
},
resolveId(id, importer) {
if (id.startsWith(VIRTUAL_RAW_PREFIX)) {
return `\0${id}`;
}
if (jit && id.startsWith('angular:jit:')) {
const filePath = normalizePath(
resolve(dirname(importer as string), id.split(';')[1]),
);
if (id.includes(':style')) {
// Mark the style path as safe so Vite's Denied ID check
// passes, then let Vite's native CSS pipeline handle the
// ?inline import (preprocessing, test.css, etc.).
markStylePathSafe(resolvedConfig, filePath);
return filePath + '?inline';
}
return toVirtualRawId(filePath);
}
// User `.html?raw` imports get rewritten to virtual ids so
// Vite's server.fs Denied ID check stays out of the way.
const rawRewrite = rewriteHtmlRawImport(id, importer);
if (rawRewrite) return rawRewrite;
// User `.scss?inline` / `.css?inline` imports: resolve and mark
// safe so Vite's native CSS pipeline handles them.
if (/\.(css|scss|sass|less)\?inline$/.test(id) && importer) {
const filePath = id.split('?')[0];
const resolved = isAbsolute(filePath)
? normalizePath(filePath)
: normalizePath(resolve(dirname(importer), filePath));
markStylePathSafe(resolvedConfig, resolved);
return resolved + '?inline';
}
// Map angular external styleUrls to the source file
if (isComponentStyleSheet(id)) {
const componentStyles = externalComponentStyles?.get(
getFilenameFromPath(id),
);
if (componentStyles) {
return componentStyles + new URL(id, 'http://localhost').search;
}
}
return undefined;
},
async load(id) {
// Virtual raw ids (templates) come from the transform-time
// substitution below and the resolveId rewrite for user
// `.html?raw` imports. Style ?inline imports now flow through
// Vite's native CSS pipeline via safeModulePaths.
const rawModule = await loadVirtualRawModule(this, id);
if (rawModule !== undefined) return rawModule;
// Vitest fallback: the module-runner calls ensureEntryFromUrl
// before transformRequest, which can skip resolveId. Mark the
// path safe here so the Denied ID check passes, then let Vite's
// CSS pipeline handle the rest.
if (/\.(css|scss|sass|less)\?inline$/.test(id)) {
markStylePathSafe(resolvedConfig, id.split('?')[0]);
}
// Map angular inline styles to the source text
if (isComponentStyleSheet(id)) {
const componentStyles = inlineComponentStyles?.get(
getFilenameFromPath(id),
);
if (componentStyles) {
return componentStyles;
}
}
return;
},
transform: {
filter: {
id: {
include: [TS_EXT_REGEX],
// `?raw` ids already carry Vite's native raw-loader output
// (`export default "<source>"`). Recompiling them as Angular/TS
// would strip that default export, so leave them to Vite (#2356).
exclude: [
/node_modules/,
'type=script',
'@ng/component',
/[?&]raw\b/,
],
},
},
async handler(code, id) {
/**
* Check for options.transformFilter
*/
if (
options?.transformFilter &&
!(options?.transformFilter(code, id) ?? true)
) {
return;
}
if (pluginOptions.useAngularCompilationAPI) {
const isAngular =
/(Component|Directive|Pipe|Injectable|NgModule)\(/.test(code);
if (!isAngular) {
return;
}
}
/**
* Skip transforming content files
*/
if (id.includes('?') && id.includes('analog-content-')) {
return;
}
/**
* Encapsulate component stylesheets that use emulated encapsulation
*/
if (pluginOptions.liveReload && isComponentStyleSheet(id)) {
const { encapsulation, componentId } =
getComponentStyleSheetMeta(id);
if (encapsulation === 'emulated' && componentId) {
const encapsulated = ngCompiler.encapsulateStyle(
code,
componentId,
);
return {
code: encapsulated,
map: null,
};
}
}
if (id.includes('.ts?')) {
// Strip the query string off the ID
// in case of a dynamically loaded file
id = id.replace(/\?(.*)/, '');
}
fileTransformMap.set(id, code);
/**
* Re-analyze on each transform
* for test(Vitest)
*/
if (isTest) {
if (isVitestVscode && !initialCompilation) {
// Do full initial compilation
pendingCompilation = performCompilation(resolvedConfig);
initialCompilation = true;
}
const tsMod = viteServer?.moduleGraph.getModuleById(id);
if (tsMod) {
const invalidated = tsMod.lastInvalidationTimestamp;
if (testWatchMode && invalidated) {
pendingCompilation = performCompilation(resolvedConfig, [id]);
}
}
}
const hasComponent = code.includes('@Component');
const templateUrls = hasComponent
? templateUrlsResolver.resolve(code, id)
: [];
const styleUrls = hasComponent
? styleUrlsResolver.resolve(code, id)
: [];
if (hasComponent && watchMode) {
for (const urlSet of [...templateUrls, ...styleUrls]) {
// `urlSet` is a string where a relative path is joined with an
// absolute path using the `|` symbol.
// For example: `./app.component.html|/home/projects/analog/src/app/app.component.html`.
const [, absoluteFileUrl] = urlSet.split('|');
this.addWatchFile(absoluteFileUrl);
}
}
if (pendingCompilation) {
await pendingCompilation;
pendingCompilation = null;
}
const typescriptResult = fileEmitter(id);
// File not in the Angular program — skip and let other plugins
// or Vite's built-in transform handle it. Warn if it looks like
// an Angular file that should have been compiled.
if (!typescriptResult) {
const isAngular =
!id.includes('@ng/component') &&
/(Component|Directive|Pipe|Injectable|NgModule)\(/.test(code);
if (isAngular) {
this.warn(
`[@analogjs/vite-plugin-angular]: "${id}" contains Angular decorators but is not in the TypeScript program. ` +
`Ensure it is included in your tsconfig.`,
);
}
return;
}
if (
typescriptResult.warnings &&
typescriptResult.warnings.length > 0
) {
this.warn(`${typescriptResult.warnings.join('\n')}`);
}
// In watch/serve, surface this module's errors immediately so the
// dev overlay points at the edited file. In build mode, defer to the
// `buildEnd` hook, which aggregates diagnostics across every file
// instead of aborting the whole build at the first errored module.
if (
watchMode &&
typescriptResult.errors &&
typescriptResult.errors.length > 0
) {
this.error(`${typescriptResult.errors.join('\n')}`);
}
let data = typescriptResult.content ?? '';
if (jit && data.includes('angular:jit:')) {
data = data.replace(
/angular:jit:style:inline;/g,
'virtual:angular:jit:style:inline;',
);
// Templates use virtual ids (no extension) so Vite's asset/CSS
// plugins don't interfere. (#2263)
templateUrls.forEach((templateUrlSet) => {
const [templateFile, resolvedTemplateUrl] =
templateUrlSet.split('|');
data = data.replace(
`angular:jit:template:file;${templateFile}`,
toVirtualRawId(resolvedTemplateUrl),
);
});
// External styles use native ?inline imports. We mark each
// path as safe in Vite's safeModulePaths so the Denied ID
// security check passes, and Vite's CSS pipeline handles
// preprocessing, test.css, and browser/node differences
// natively. (#2263, #2310)
styleUrls.forEach((styleUrlSet) => {
const [styleFile, resolvedStyleUrl] = styleUrlSet.split('|');
markStylePathSafe(resolvedConfig, resolvedStyleUrl);
data = data.replace(
`angular:jit:style:file;${styleFile}`,
resolvedStyleUrl + '?inline',
);
});
}
if (typescriptResult.map) {
// TS emits `//# sourceMappingURL=foo.js.map` at the end of the
// .js content, but the .map file isn't served by Vite — we
// return the map object directly. Strip the stale reference so
// downstream tools don't see two sourceMappingURL comments.
data = data.replace(/\s*\/\/# sourceMappingURL=[^\r\n]*\s*$/, '');
}
return {
code: data,
map: typescriptResult.map ?? null,
};
},
},
closeBundle() {
declarationFiles.forEach(
({ declarationFileDir, declarationPath, data }) => {
mkdirSync(declarationFileDir, { recursive: true });
writeFileSync(declarationPath, data, 'utf-8');
},
);
// Tear down the persistent compilation instance at end of build so it
// does not leak memory across unrelated Vite invocations.
angularCompilation?.close?.();
angularCompilation = undefined;
},
};
}
const compilationPlugin = pluginOptions.fastCompile
? fastCompilePlugin({
tsconfigGetter: pluginOptions.tsconfigGetter,
workspaceRoot: pluginOptions.workspaceRoot,
inlineStylesExtension: pluginOptions.inlineStylesExtension,
jit,
liveReload: pluginOptions.liveReload,
supportedBrowsers: pluginOptions.supportedBrowsers,
transformFilter: options?.transformFilter,
isTest,
isAstroIntegration,
fastCompileMode: pluginOptions.fastCompileMode,
fastCompileEngine: pluginOptions.fastCompileEngine,
})
: angularPlugin();
// OXC engine only: link pre-compiled Angular libraries (`ɵɵngDeclare*`
// → `ɵɵdefine*`) using OXC's native Rust linker. Without this, those
// libraries fall back to runtime JIT linking which pulls
// `@angular/compiler` into the browser bundle. Skipped on the TS
// engine path, which has its own dts-reader covering the same need.
const linkerPlugin =
pluginOptions.fastCompile && pluginOptions.fastCompileEngine === 'oxc'
? oxcLinkerPlugin()
: (false as unknown as Plugin);
// Both engines use Analog's `JavaScriptTransformer`-backed optimizer.
// OXC's `optimizeAngularPackage` leaves `@angular/core/fesm2022/core.mjs`
// essentially untouched, so unused public re-exports (including the JIT
// runtime) survive tree-shaking and ~150KB extra ships to the client.
// Revisit `oxcOptimizerPlugin` once upstream closes the gap.
const optimizerPlugin = buildOptimizerPlugin({
supportedBrowsers: pluginOptions.supportedBrowsers,
jit,
});
return [
replaceFiles(pluginOptions.fileReplacements, pluginOptions.workspaceRoot),
compilationPlugin,
linkerPlugin,
!pluginOptions.fastCompile &&
pluginOptions.liveReload &&
liveReloadPlugin({ classNames, fileEmitter }),
...(isTest && !isStackBlitz
? angularVitestPlugins((id) => outputFiles.get(normalizePath(id))?.map)
: []),
(jit &&
jitPlugin({
inlineStylesExtension: pluginOptions.inlineStylesExtension,
})) as Plugin,
optimizerPlugin,
routerPlugin(),
angularFullVersion < 190004 && pendingTasksPlugin(),
nxFolderPlugin(),
]
.flat()
.filter(Boolean) as Plugin[];
function findIncludes() {
const workspaceRoot = normalizePath(resolve(pluginOptions.workspaceRoot));
// Map include patterns to absolute workspace paths
const globs = [
...pluginOptions.include.map((glob) => `${workspaceRoot}${glob}`),
];
// Discover TypeScript files using tinyglobby
return globSync(globs, {
dot: true,
absolute: true,
});
}
function resolveTsConfigPath() {
const tsconfigValue = pluginOptions.tsconfigGetter();
return getTsConfigPath(
tsConfigResolutionContext!.root,
tsconfigValue,
tsConfigResolutionContext!.isProd,
isTest,
tsConfigResolutionContext!.isLib,
);
}
/**
* Perform compilation using Angular's private Compilation API.
*
* Key differences from the standard `performCompilation` path:
* 1. The compilation instance is reused across rebuilds (nullish-coalescing
* assignment below) so Angular retains prior state and can diff it to
* produce `templateUpdates` for HMR.
* 2. `ids` (modified files) are forwarded to both the source-file cache and
* `angularCompilation.update()` so that incremental re-analysis is
* scoped to what actually changed.
* 3. `fileReplacements` are converted and passed into Angular's host via
* `toAngularCompilationFileReplacements`.
* 4. `templateUpdates` from the compilation result are mapped back to
* file-level HMR metadata (`hmrUpdateCode`, `hmrEligible`, `classNames`).
*/
async function performAngularCompilation(
config: ResolvedConfig,
ids?: string[],
) {
// Reuse the existing instance so Angular can diff against prior state.
angularCompilation ??= await (
createAngularCompilation as typeof createAngularCompilationType
)(!!pluginOptions.jit, false);
const modifiedFiles = ids?.length
? new Set(ids.map((file) => normalizePath(file)))
: undefined;
if (modifiedFiles?.size) {
sourceFileCache.invalidate(modifiedFiles);
}
// Notify Angular of modified files before re-initialization so it can
// scope its incremental analysis.
if (modifiedFiles?.size && angularCompilation.update) {
await angularCompilation.update(modifiedFiles);
}
const resolvedTsConfigPath = resolveTsConfigPath();
const compilationResult = await angularCompilation.initialize(
resolvedTsConfigPath,
{
// Convert Analog's browser-style `{ replace, with }` entries into the
// `Record<string, string>` shape that Angular's AngularHostOptions
// expects. SSR-only replacements (`{ replace, ssr }`) are intentionally
// excluded — they stay on the Vite runtime side.
fileReplacements: toAngularCompilationFileReplacements(
pluginOptions.fileReplacements,
pluginOptions.workspaceRoot,
),
modifiedFiles,
async transformStylesheet(
data,
containingFile,
resourceFile,
order,
className,
) {
if (pluginOptions.liveReload) {
const id = createHash('sha256')
.update(containingFile)
.update(className as string)
.update(String(order))
.update(data)
.digest('hex');
const filename = id + '.' + pluginOptions.inlineStylesExtension;
inlineComponentStyles!.set(filename, data);
return filename;
}
const filename =
resourceFile ??
containingFile.replace('.ts', `.${options?.inlineStylesExtension}`);
let stylesheetResult;
try {
stylesheetResult = await preprocessCSS(
data,
`${filename}?direct`,
resolvedConfig,
);
} catch (e) {
console.error(`${e}`);
}
return stylesheetResult?.code || '';