forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapplication-code-bundle.ts
755 lines (665 loc) · 25.8 KB
/
application-code-bundle.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { BuildOptions, PartialMessage } from 'esbuild';
import assert from 'node:assert';
import { createHash } from 'node:crypto';
import { extname, relative } from 'node:path';
import type { NormalizedApplicationBuildOptions } from '../../builders/application/options';
import { ExperimentalPlatform } from '../../builders/application/schema';
import { allowMangle } from '../../utils/environment-options';
import {
SERVER_APP_ENGINE_MANIFEST_FILENAME,
SERVER_APP_MANIFEST_FILENAME,
} from '../../utils/server-rendering/manifest';
import { AngularCompilation, NoopCompilation } from '../angular/compilation';
import { createCompilerPlugin } from './angular/compiler-plugin';
import { ComponentStylesheetBundler } from './angular/component-stylesheets';
import { SourceFileCache } from './angular/source-file-cache';
import { createAngularLocalizeInitWarningPlugin } from './angular-localize-init-warning-plugin';
import { BundlerOptionsFactory } from './bundler-context';
import { createCompilerPluginOptions } from './compiler-plugin-options';
import { createExternalPackagesPlugin } from './external-packages-plugin';
import { createAngularLocaleDataPlugin } from './i18n-locale-plugin';
import type { LoadResultCache } from './load-result-cache';
import { createLoaderImportAttributePlugin } from './loader-import-attribute-plugin';
import { createRxjsEsmResolutionPlugin } from './rxjs-esm-resolution-plugin';
import { createServerBundleMetadata } from './server-bundle-metadata-plugin';
import { createSourcemapIgnorelistPlugin } from './sourcemap-ignorelist-plugin';
import { SERVER_GENERATED_EXTERNALS, getFeatureSupport, isZonelessApp } from './utils';
import { createVirtualModulePlugin } from './virtual-module-plugin';
import { createWasmPlugin } from './wasm-plugin';
export function createBrowserCodeBundleOptions(
options: NormalizedApplicationBuildOptions,
target: string[],
sourceFileCache: SourceFileCache,
stylesheetBundler: ComponentStylesheetBundler,
angularCompilation: AngularCompilation,
templateUpdates: Map<string, string> | undefined,
): BundlerOptionsFactory {
return (loadCache) => {
const { entryPoints, outputNames, polyfills } = options;
const pluginOptions = createCompilerPluginOptions(
options,
sourceFileCache,
loadCache,
templateUpdates,
);
const zoneless = isZonelessApp(polyfills);
const buildOptions: BuildOptions = {
...getEsBuildCommonOptions(options),
platform: 'browser',
// Note: `es2015` is needed for RxJS v6. If not specified, `module` would
// match and the ES5 distribution would be bundled and ends up breaking at
// runtime with the RxJS testing library.
// More details: https://github.com/angular/angular-cli/issues/25405.
mainFields: ['es2020', 'es2015', 'browser', 'module', 'main'],
entryNames: outputNames.bundles,
entryPoints,
target,
supported: getFeatureSupport(target, zoneless),
plugins: [
createLoaderImportAttributePlugin(),
createWasmPlugin({ allowAsync: zoneless, cache: loadCache }),
createSourcemapIgnorelistPlugin(),
createAngularLocalizeInitWarningPlugin(),
createCompilerPlugin(
// JS/TS options
pluginOptions,
angularCompilation,
// Component stylesheet bundler
stylesheetBundler,
),
],
};
if (options.plugins) {
buildOptions.plugins?.push(...options.plugins);
}
appendOptionsForExternalPackages(options, buildOptions);
return buildOptions;
};
}
export function createBrowserPolyfillBundleOptions(
options: NormalizedApplicationBuildOptions,
target: string[],
sourceFileCache: SourceFileCache,
stylesheetBundler: ComponentStylesheetBundler,
): BuildOptions | BundlerOptionsFactory | undefined {
const namespace = 'angular:polyfills';
const polyfillBundleOptions = getEsBuildCommonPolyfillsOptions(
options,
namespace,
true,
sourceFileCache.loadResultCache,
);
if (!polyfillBundleOptions) {
return;
}
const { outputNames, polyfills } = options;
const hasTypeScriptEntries = polyfills?.some((entry) => /\.[cm]?tsx?$/.test(entry));
const buildOptions: BuildOptions = {
...polyfillBundleOptions,
platform: 'browser',
// Note: `es2015` is needed for RxJS v6. If not specified, `module` would
// match and the ES5 distribution would be bundled and ends up breaking at
// runtime with the RxJS testing library.
// More details: https://github.com/angular/angular-cli/issues/25405.
mainFields: ['es2020', 'es2015', 'browser', 'module', 'main'],
entryNames: outputNames.bundles,
target,
entryPoints: {
'polyfills': namespace,
},
};
// Only add the Angular TypeScript compiler if TypeScript files are provided in the polyfills
if (hasTypeScriptEntries) {
buildOptions.plugins ??= [];
const pluginOptions = createCompilerPluginOptions(
options,
sourceFileCache,
);
buildOptions.plugins.push(
createCompilerPlugin(
// JS/TS options
pluginOptions,
// Browser compilation handles the actual Angular code compilation
new NoopCompilation(),
// Component stylesheet options are unused for polyfills but required by the plugin
stylesheetBundler,
),
);
}
// Use an options factory to allow fully incremental bundling when no TypeScript files are present.
// The TypeScript compilation is not currently integrated into the bundler invalidation so
// cannot be used with fully incremental bundling yet.
return hasTypeScriptEntries ? buildOptions : () => buildOptions;
}
export function createServerPolyfillBundleOptions(
options: NormalizedApplicationBuildOptions,
target: string[],
loadResultCache: LoadResultCache | undefined,
): BundlerOptionsFactory | undefined {
const serverPolyfills: string[] = [];
const polyfillsFromConfig = new Set(options.polyfills);
const isNodePlatform = options.ssrOptions?.platform !== ExperimentalPlatform.Neutral;
if (!isZonelessApp(options.polyfills)) {
serverPolyfills.push(isNodePlatform ? 'zone.js/node' : 'zone.js');
}
if (
polyfillsFromConfig.has('@angular/localize') ||
polyfillsFromConfig.has('@angular/localize/init')
) {
serverPolyfills.push('@angular/localize/init');
}
serverPolyfills.push('@angular/platform-server/init');
const namespace = 'angular:polyfills-server';
const polyfillBundleOptions = getEsBuildCommonPolyfillsOptions(
{
...options,
polyfills: serverPolyfills,
},
namespace,
false,
loadResultCache,
);
if (!polyfillBundleOptions) {
return;
}
const jsBanner: string[] = [];
if (polyfillBundleOptions.external?.length) {
jsBanner.push(`globalThis['ngServerMode'] = true;`);
}
if (isNodePlatform) {
// Note: Needed as esbuild does not provide require shims / proxy from ESModules.
// See: https://github.com/evanw/esbuild/issues/1921.
jsBanner.push(
`import { createRequire } from 'node:module';`,
`globalThis['require'] ??= createRequire(import.meta.url);`,
);
}
const buildOptions: BuildOptions = {
...polyfillBundleOptions,
platform: isNodePlatform ? 'node' : 'neutral',
outExtension: { '.js': '.mjs' },
// Note: `es2015` is needed for RxJS v6. If not specified, `module` would
// match and the ES5 distribution would be bundled and ends up breaking at
// runtime with the RxJS testing library.
// More details: https://github.com/angular/angular-cli/issues/25405.
mainFields: ['es2020', 'es2015', 'module', 'main'],
entryNames: '[name]',
banner: {
js: jsBanner.join('\n'),
},
target,
entryPoints: {
'polyfills.server': namespace,
},
};
buildOptions.plugins ??= [];
buildOptions.plugins.push(createServerBundleMetadata());
return () => buildOptions;
}
export function createServerMainCodeBundleOptions(
options: NormalizedApplicationBuildOptions,
target: string[],
sourceFileCache: SourceFileCache,
stylesheetBundler: ComponentStylesheetBundler,
): BundlerOptionsFactory {
const {
serverEntryPoint: mainServerEntryPoint,
workspaceRoot,
outputMode,
externalPackages,
ssrOptions,
polyfills,
} = options;
assert(
mainServerEntryPoint,
'createServerCodeBundleOptions should not be called without a defined serverEntryPoint.',
);
return (loadResultCache) => {
const pluginOptions = createCompilerPluginOptions(options, sourceFileCache, loadResultCache);
const mainServerNamespace = 'angular:main-server';
const mainServerInjectManifestNamespace = 'angular:main-server-inject-manifest';
const zoneless = isZonelessApp(polyfills);
const entryPoints: Record<string, string> = {
'main.server': mainServerNamespace,
};
const ssrEntryPoint = ssrOptions?.entry;
const isOldBehaviour = !outputMode;
if (ssrEntryPoint && isOldBehaviour) {
// Old behavior: 'server.ts' was bundled together with the SSR (Server-Side Rendering) code.
// This approach combined server-side logic and rendering into a single bundle.
entryPoints['server'] = ssrEntryPoint;
}
const buildOptions: BuildOptions = {
...getEsBuildServerCommonOptions(options),
target,
banner: {
js: `import './polyfills.server.mjs';`,
},
entryPoints,
supported: getFeatureSupport(target, zoneless),
plugins: [
createWasmPlugin({ allowAsync: zoneless, cache: loadResultCache }),
createSourcemapIgnorelistPlugin(),
createAngularLocalizeInitWarningPlugin(),
createCompilerPlugin(
// JS/TS options
pluginOptions,
// Browser compilation handles the actual Angular code compilation
new NoopCompilation(),
// Component stylesheet bundler
stylesheetBundler,
),
],
};
buildOptions.plugins ??= [];
if (!externalPackages) {
buildOptions.plugins.push(createRxjsEsmResolutionPlugin());
}
// Mark manifest and polyfills file as external as these are generated by a different bundle step.
(buildOptions.external ??= []).push(...SERVER_GENERATED_EXTERNALS);
const isNodePlatform = options.ssrOptions?.platform !== ExperimentalPlatform.Neutral;
if (!isNodePlatform) {
// `@angular/platform-server` lazily depends on `xhr2` for XHR usage with the HTTP client.
// Since `xhr2` has Node.js dependencies, it cannot be used when targeting non-Node.js platforms.
// Note: The framework already issues a warning when using XHR with SSR.
buildOptions.external.push('xhr2');
}
buildOptions.plugins.push(
createServerBundleMetadata(),
createVirtualModulePlugin({
namespace: mainServerInjectManifestNamespace,
cache: loadResultCache,
entryPointOnly: false,
loadContent: async () => {
const contents: string[] = [
// Configure `@angular/ssr` manifest.
`import manifest from './${SERVER_APP_MANIFEST_FILENAME}';`,
`import { ɵsetAngularAppManifest } from '@angular/ssr';`,
`ɵsetAngularAppManifest(manifest);`,
];
return {
contents: contents.join('\n'),
loader: 'js',
resolveDir: workspaceRoot,
};
},
}),
createVirtualModulePlugin({
namespace: mainServerNamespace,
cache: loadResultCache,
loadContent: async () => {
const mainServerEntryPointJsImport = entryFileToWorkspaceRelative(
workspaceRoot,
mainServerEntryPoint,
);
const contents: string[] = [
// Inject manifest
`import '${mainServerInjectManifestNamespace}';`,
// Add @angular/ssr exports
`export {
ɵdestroyAngularServerApp,
ɵextractRoutesAndCreateRouteTree,
ɵgetOrCreateAngularServerApp,
} from '@angular/ssr';`,
// Need for HMR
`export { ɵresetCompiledComponents } from '@angular/core';`,
// Re-export all symbols including default export from 'main.server.ts'
`export { default } from '${mainServerEntryPointJsImport}';`,
`export * from '${mainServerEntryPointJsImport}';`,
];
return {
contents: contents.join('\n'),
loader: 'js',
resolveDir: workspaceRoot,
};
},
}),
);
if (options.plugins) {
buildOptions.plugins.push(...options.plugins);
}
appendOptionsForExternalPackages(options, buildOptions);
return buildOptions;
};
}
export function createSsrEntryCodeBundleOptions(
options: NormalizedApplicationBuildOptions,
target: string[],
sourceFileCache: SourceFileCache,
stylesheetBundler: ComponentStylesheetBundler,
): BundlerOptionsFactory {
const { workspaceRoot, ssrOptions, externalPackages } = options;
const serverEntryPoint = ssrOptions?.entry;
assert(
serverEntryPoint,
'createSsrEntryCodeBundleOptions should not be called without a defined serverEntryPoint.',
);
return (loadResultCache) => {
const pluginOptions = createCompilerPluginOptions(options, sourceFileCache, loadResultCache);
const ssrEntryNamespace = 'angular:ssr-entry';
const ssrInjectManifestNamespace = 'angular:ssr-entry-inject-manifest';
const isNodePlatform = options.ssrOptions?.platform !== ExperimentalPlatform.Neutral;
const jsBanner: string[] = [];
if (options.externalDependencies?.length) {
jsBanner.push(`globalThis['ngServerMode'] = true;`);
}
if (isNodePlatform) {
// Note: Needed as esbuild does not provide require shims / proxy from ESModules.
// See: https://github.com/evanw/esbuild/issues/1921.
jsBanner.push(
`import { createRequire } from 'node:module';`,
`globalThis['require'] ??= createRequire(import.meta.url);`,
);
}
const buildOptions: BuildOptions = {
...getEsBuildServerCommonOptions(options),
target,
banner: {
js: jsBanner.join('\n'),
},
entryPoints: {
'server': ssrEntryNamespace,
},
supported: getFeatureSupport(target, true),
plugins: [
createSourcemapIgnorelistPlugin(),
createAngularLocalizeInitWarningPlugin(),
createCompilerPlugin(
// JS/TS options
pluginOptions,
// Browser compilation handles the actual Angular code compilation
new NoopCompilation(),
// Component stylesheet bundler
stylesheetBundler,
),
],
};
buildOptions.plugins ??= [];
if (!externalPackages) {
buildOptions.plugins.push(createRxjsEsmResolutionPlugin());
}
// Mark manifest file as external. As this will be generated later on.
(buildOptions.external ??= []).push('*/main.server.mjs', ...SERVER_GENERATED_EXTERNALS);
if (!isNodePlatform) {
// `@angular/platform-server` lazily depends on `xhr2` for XHR usage with the HTTP client.
// Since `xhr2` has Node.js dependencies, it cannot be used when targeting non-Node.js platforms.
// Note: The framework already issues a warning when using XHR with SSR.
buildOptions.external.push('xhr2');
}
buildOptions.plugins.push(
createServerBundleMetadata({ ssrEntryBundle: true }),
createVirtualModulePlugin({
namespace: ssrInjectManifestNamespace,
cache: loadResultCache,
entryPointOnly: false,
loadContent: () => {
const contents: string[] = [
// Configure `@angular/ssr` app engine manifest.
`import manifest from './${SERVER_APP_ENGINE_MANIFEST_FILENAME}';`,
`import { ɵsetAngularAppEngineManifest } from '@angular/ssr';`,
`ɵsetAngularAppEngineManifest(manifest);`,
];
return {
contents: contents.join('\n'),
loader: 'js',
resolveDir: workspaceRoot,
};
},
}),
createVirtualModulePlugin({
namespace: ssrEntryNamespace,
cache: loadResultCache,
loadContent: () => {
const serverEntryPointJsImport = entryFileToWorkspaceRelative(
workspaceRoot,
serverEntryPoint,
);
const contents: string[] = [
// Configure `@angular/ssr` app engine manifest.
`import '${ssrInjectManifestNamespace}';`,
// Re-export all symbols including default export
`import * as server from '${serverEntryPointJsImport}';`,
`export * from '${serverEntryPointJsImport}';`,
// The below is needed to avoid
// `Import "default" will always be undefined because there is no matching export` warning when no default is present.
`const defaultExportName = 'default';`,
`export default server[defaultExportName]`,
// Add @angular/ssr exports
`export { AngularAppEngine } from '@angular/ssr';`,
];
return {
contents: contents.join('\n'),
loader: 'js',
resolveDir: workspaceRoot,
};
},
}),
);
if (options.plugins) {
buildOptions.plugins.push(...options.plugins);
}
appendOptionsForExternalPackages(options, buildOptions);
return buildOptions;
};
}
function getEsBuildServerCommonOptions(options: NormalizedApplicationBuildOptions): BuildOptions {
const isNodePlatform = options.ssrOptions?.platform !== ExperimentalPlatform.Neutral;
const commonOptons = getEsBuildCommonOptions(options);
commonOptons.define ??= {};
commonOptons.define['ngServerMode'] = 'true';
return {
...commonOptons,
platform: isNodePlatform ? 'node' : 'neutral',
outExtension: { '.js': '.mjs' },
// Note: `es2015` is needed for RxJS v6. If not specified, `module` would
// match and the ES5 distribution would be bundled and ends up breaking at
// runtime with the RxJS testing library.
// More details: https://github.com/angular/angular-cli/issues/25405.
mainFields: ['es2020', 'es2015', 'module', 'main'],
entryNames: '[name]',
};
}
function getEsBuildCommonOptions(options: NormalizedApplicationBuildOptions): BuildOptions {
const {
workspaceRoot,
outExtension,
optimizationOptions,
sourcemapOptions,
tsconfig,
externalDependencies,
outputNames,
preserveSymlinks,
jit,
loaderExtensions,
jsonLogs,
i18nOptions,
customConditions,
} = options;
// Ensure unique hashes for i18n translation changes when using post-process inlining.
// This hash value is added as a footer to each file and ensures that the output file names (with hashes)
// change when translation files have changed. If this is not done the post processed files may have
// different content but would retain identical production file names which would lead to browser caching problems.
let footer;
if (i18nOptions.shouldInline) {
// Update file hashes to include translation file content
const i18nHash = Object.values(i18nOptions.locales).reduce(
(data, locale) => data + locale.files.map((file) => file.integrity || '').join('|'),
'',
);
footer = { js: `/**i18n:${createHash('sha256').update(i18nHash).digest('hex')}*/` };
}
// Core conditions that are always included
const conditions = [
// Required to support rxjs 7.x which will use es5 code if this condition is not present
'es2015',
'es2020',
];
// Append custom conditions if present
if (customConditions) {
conditions.push(...customConditions);
} else {
// Include default conditions
conditions.push('module');
conditions.push(optimizationOptions.scripts ? 'production' : 'development');
}
return {
absWorkingDir: workspaceRoot,
format: 'esm',
bundle: true,
packages: 'bundle',
assetNames: outputNames.media,
conditions,
resolveExtensions: ['.ts', '.tsx', '.mjs', '.js', '.cjs'],
metafile: true,
legalComments: options.extractLicenses ? 'none' : 'eof',
logLevel: options.verbose && !jsonLogs ? 'debug' : 'silent',
minifyIdentifiers: optimizationOptions.scripts && allowMangle,
minifySyntax: optimizationOptions.scripts,
minifyWhitespace: optimizationOptions.scripts,
pure: ['forwardRef'],
outdir: workspaceRoot,
outExtension: outExtension ? { '.js': `.${outExtension}` } : undefined,
sourcemap: sourcemapOptions.scripts && (sourcemapOptions.hidden ? 'external' : true),
sourcesContent: sourcemapOptions.sourcesContent,
splitting: true,
chunkNames: options.namedChunks ? '[name]-[hash]' : 'chunk-[hash]',
tsconfig,
external: externalDependencies ? [...externalDependencies] : undefined,
write: false,
preserveSymlinks,
define: {
...options.define,
// Only set to false when script optimizations are enabled. It should not be set to true because
// Angular turns `ngDevMode` into an object for development debugging purposes when not defined
// which a constant true value would break.
...(optimizationOptions.scripts ? { 'ngDevMode': 'false' } : undefined),
'ngJitMode': jit ? 'true' : 'false',
'ngServerMode': 'false',
'ngHmrMode': options.templateUpdates ? 'true' : 'false',
},
loader: loaderExtensions,
footer,
};
}
function getEsBuildCommonPolyfillsOptions(
options: NormalizedApplicationBuildOptions,
namespace: string,
tryToResolvePolyfillsAsRelative: boolean,
loadResultCache: LoadResultCache | undefined,
): BuildOptions | undefined {
const { jit, workspaceRoot, i18nOptions } = options;
const buildOptions: BuildOptions = {
...getEsBuildCommonOptions(options),
splitting: false,
plugins: [createSourcemapIgnorelistPlugin()],
};
let polyfills = options.polyfills ? [...options.polyfills] : [];
// Angular JIT mode requires the runtime compiler
if (jit) {
polyfills.unshift('@angular/compiler');
}
// Add Angular's global locale data if i18n options are present.
// Locale data should go first so that project provided polyfill code can augment if needed.
let needLocaleDataPlugin = false;
if (i18nOptions.shouldInline) {
// Remove localize polyfill as this is not needed for build time i18n.
polyfills = polyfills.filter((path) => !path.startsWith('@angular/localize'));
// Add locale data for all active locales
// TODO: Inject each individually within the inlining process itself
for (const locale of i18nOptions.inlineLocales) {
polyfills.unshift(`angular:locale/data:${locale}`);
}
needLocaleDataPlugin = true;
} else if (i18nOptions.hasDefinedSourceLocale) {
// When not inlining and a source local is present, use the source locale data directly
polyfills.unshift(`angular:locale/data:${i18nOptions.sourceLocale}`);
needLocaleDataPlugin = true;
}
if (needLocaleDataPlugin) {
buildOptions.plugins?.push(createAngularLocaleDataPlugin());
}
if (polyfills.length === 0) {
return;
}
buildOptions.plugins?.push(
createVirtualModulePlugin({
namespace,
cache: loadResultCache,
loadContent: async (_, build) => {
let polyfillPaths = polyfills;
let warnings: PartialMessage[] | undefined;
if (tryToResolvePolyfillsAsRelative) {
polyfillPaths = await Promise.all(
polyfills.map(async (path) => {
if (path.startsWith('zone.js') || !extname(path)) {
return path;
}
const potentialPathRelative = './' + path;
const result = await build.resolve(potentialPathRelative, {
kind: 'import-statement',
resolveDir: workspaceRoot,
});
return result.path ? potentialPathRelative : path;
}),
);
}
// Generate module contents with an import statement per defined polyfill
let contents = polyfillPaths
.map((file) => `import '${file.replace(/\\/g, '/')}';`)
.join('\n');
// The below should be done after loading `$localize` as otherwise the locale will be overridden.
if (i18nOptions.shouldInline) {
// When inlining, a placeholder is used to allow the post-processing step to inject the $localize locale identifier.
contents += '(globalThis.$localize ??= {}).locale = "___NG_LOCALE_INSERT___";\n';
} else if (i18nOptions.hasDefinedSourceLocale) {
// If not inlining translations and source locale is defined, inject the locale specifier.
contents += `(globalThis.$localize ??= {}).locale = "${i18nOptions.sourceLocale}";\n`;
}
return {
contents,
loader: 'js',
warnings,
resolveDir: workspaceRoot,
};
},
}),
);
return buildOptions;
}
function entryFileToWorkspaceRelative(workspaceRoot: string, entryFile: string): string {
return (
'./' +
relative(workspaceRoot, entryFile)
.replace(/.[mc]?ts$/, '')
.replace(/\\/g, '/')
);
}
function appendOptionsForExternalPackages(
options: NormalizedApplicationBuildOptions,
buildOptions: BuildOptions,
): void {
if (!options.externalPackages) {
return;
}
buildOptions.plugins ??= [];
// Package files affected by a customized loader should not be implicitly marked as external
if (options.loaderExtensions || options.plugins || typeof options.externalPackages === 'object') {
// Plugin must be added after custom plugins to ensure any added loader options are considered
buildOptions.plugins.push(
createExternalPackagesPlugin(
options.externalPackages !== true ? options.externalPackages : undefined,
),
);
buildOptions.packages = undefined;
} else {
// Safe to use the packages external option directly
buildOptions.packages = 'external';
}
}