forked from angular/angular-cli
/
application-code-bundle.ts
409 lines (364 loc) · 14.3 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
/**
* @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.io/license
*/
import type { BuildOptions } from 'esbuild';
import assert from 'node:assert';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { extname, join, relative } from 'node:path';
import type { NormalizedApplicationBuildOptions } from '../../builders/application/options';
import { allowMangle } from '../../utils/environment-options';
import { createCompilerPlugin } from './angular/compiler-plugin';
import { SourceFileCache } from './angular/source-file-cache';
import { createCompilerPluginOptions } from './compiler-plugin-options';
import { createAngularLocaleDataPlugin } from './i18n-locale-plugin';
import { createRxjsEsmResolutionPlugin } from './rxjs-esm-resolution-plugin';
import { createSourcemapIgnorelistPlugin } from './sourcemap-ignorelist-plugin';
import { getFeatureSupport } from './utils';
import { createVirtualModulePlugin } from './virtual-module-plugin';
export function createBrowserCodeBundleOptions(
options: NormalizedApplicationBuildOptions,
target: string[],
sourceFileCache?: SourceFileCache,
): BuildOptions {
const { workspaceRoot, entryPoints, outputNames, jit } = options;
const { pluginOptions, styleOptions } = createCompilerPluginOptions(
options,
target,
sourceFileCache,
);
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),
plugins: [
createSourcemapIgnorelistPlugin(),
createCompilerPlugin(
// JS/TS options
pluginOptions,
// Component stylesheet options
styleOptions,
),
],
};
if (options.externalPackages) {
buildOptions.packages = 'external';
}
const polyfills = options.polyfills ? [...options.polyfills] : [];
// Angular JIT mode requires the runtime compiler
if (jit) {
polyfills.push('@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 (options.i18nOptions.shouldInline) {
// When inlining, a placeholder is used to allow the post-processing step to inject the $localize locale identifier
polyfills.unshift('angular:locale/placeholder');
buildOptions.plugins?.unshift(
createVirtualModulePlugin({
namespace: 'angular:locale/placeholder',
entryPointOnly: false,
loadContent: () => ({
contents: `(globalThis.$localize ??= {}).locale = "___NG_LOCALE_INSERT___";\n`,
loader: 'js',
resolveDir: workspaceRoot,
}),
}),
);
// Add locale data for all active locales
// TODO: Inject each individually within the inlining process itself
for (const locale of options.i18nOptions.inlineLocales) {
polyfills.unshift(`angular:locale/data:${locale}`);
}
needLocaleDataPlugin = true;
} else if (options.i18nOptions.hasDefinedSourceLocale) {
// When not inlining and a source local is present, use the source locale data directly
polyfills.unshift(`angular:locale/data:${options.i18nOptions.sourceLocale}`);
needLocaleDataPlugin = true;
}
if (needLocaleDataPlugin) {
buildOptions.plugins?.push(createAngularLocaleDataPlugin());
}
// Add polyfill entry point if polyfills are present
if (polyfills.length) {
const namespace = 'angular:polyfills';
buildOptions.entryPoints = {
...buildOptions.entryPoints,
'polyfills': namespace,
};
buildOptions.plugins?.unshift(
createVirtualModulePlugin({
namespace,
loadContent: async (_, build) => {
let hasLocalizePolyfill = false;
const polyfillPaths = await Promise.all(
polyfills.map(async (path) => {
hasLocalizePolyfill ||= path.startsWith('@angular/localize');
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;
}),
);
if (!options.i18nOptions.shouldInline && !hasLocalizePolyfill) {
// Cannot use `build.resolve` here since it does not allow overriding the external options
// and the actual presence of the `@angular/localize` package needs to be checked here.
const workspaceRequire = createRequire(workspaceRoot + '/');
try {
workspaceRequire.resolve('@angular/localize');
// The resolve call above will throw if not found
polyfillPaths.push('@angular/localize/init');
} catch {}
}
// Generate module contents with an import statement per defined polyfill
let contents = polyfillPaths
.map((file) => `import '${file.replace(/\\/g, '/')}';`)
.join('\n');
// If not inlining translations and source locale is defined, inject the locale specifier
if (!options.i18nOptions.shouldInline && options.i18nOptions.hasDefinedSourceLocale) {
contents += `(globalThis.$localize ??= {}).locale = "${options.i18nOptions.sourceLocale}";\n`;
}
return {
contents,
loader: 'js',
resolveDir: workspaceRoot,
};
},
}),
);
}
return buildOptions;
}
/**
* Create an esbuild 'build' options object for the server bundle.
* @param options The builder's user-provider normalized options.
* @returns An esbuild BuildOptions object.
*/
export function createServerCodeBundleOptions(
options: NormalizedApplicationBuildOptions,
target: string[],
sourceFileCache: SourceFileCache,
): BuildOptions {
const {
jit,
serverEntryPoint,
workspaceRoot,
ssrOptions,
watch,
externalPackages,
prerenderOptions,
} = options;
assert(
serverEntryPoint,
'createServerCodeBundleOptions should not be called without a defined serverEntryPoint.',
);
const { pluginOptions, styleOptions } = createCompilerPluginOptions(
options,
target,
sourceFileCache,
);
const mainServerNamespace = 'angular:main-server';
const ssrEntryNamespace = 'angular:ssr-entry';
const entryPoints: Record<string, string> = {
'main.server': mainServerNamespace,
};
const ssrEntryPoint = ssrOptions?.entry;
if (ssrEntryPoint) {
entryPoints['server'] = ssrEntryNamespace;
}
const buildOptions: BuildOptions = {
...getEsBuildCommonOptions(options),
platform: 'node',
// TODO: Invesigate why enabling `splitting` in JIT mode causes an "'@angular/compiler' is not available" error.
splitting: !jit,
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]',
target,
banner: {
// Note: Needed as esbuild does not provide require shims / proxy from ESModules.
// See: https://github.com/evanw/esbuild/issues/1921.
js: [
`import { createRequire } from 'node:module';`,
`globalThis['require'] ??= createRequire(import.meta.url);`,
].join('\n'),
},
entryPoints,
supported: getFeatureSupport(target),
plugins: [
createSourcemapIgnorelistPlugin(),
createCompilerPlugin(
// JS/TS options
{ ...pluginOptions, noopTypeScriptCompilation: true },
// Component stylesheet options
styleOptions,
),
],
};
buildOptions.plugins ??= [];
if (externalPackages) {
buildOptions.packages = 'external';
} else {
buildOptions.plugins.push(createRxjsEsmResolutionPlugin());
}
const polyfills: string[] = [];
if (options.polyfills?.includes('zone.js')) {
polyfills.push(`import 'zone.js/node';`);
}
if (jit) {
polyfills.push(`import '@angular/compiler';`);
}
polyfills.push(`import '@angular/platform-server/init';`);
buildOptions.plugins.push(
createVirtualModulePlugin({
namespace: mainServerNamespace,
loadContent: async () => {
const mainServerEntryPoint = relative(workspaceRoot, serverEntryPoint).replace(/\\/g, '/');
const contents = [
...polyfills,
`import moduleOrBootstrapFn from './${mainServerEntryPoint}';`,
`export default moduleOrBootstrapFn;`,
`export * from './${mainServerEntryPoint}';`,
`export { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/platform-server';`,
];
if (watch) {
contents.push(`export { ɵresetCompiledComponents } from '@angular/core';`);
}
if (!options.i18nOptions.shouldInline) {
// Cannot use `build.resolve` here since it does not allow overriding the external options
// and the actual presence of the `@angular/localize` package needs to be checked here.
const workspaceRequire = createRequire(workspaceRoot + '/');
try {
workspaceRequire.resolve('@angular/localize');
// The resolve call above will throw if not found
contents.push(`import '@angular/localize/init';`);
} catch {}
}
if (options.i18nOptions.shouldInline) {
// When inlining, a placeholder is used to allow the post-processing step to inject the $localize locale identifier
contents.push('(globalThis.$localize ??= {}).locale = "___NG_LOCALE_INSERT___";');
} else if (options.i18nOptions.hasDefinedSourceLocale) {
// If not inlining translations and source locale is defined, inject the locale specifier
contents.push(
`(globalThis.$localize ??= {}).locale = "${options.i18nOptions.sourceLocale}";`,
);
}
if (prerenderOptions?.discoverRoutes) {
// We do not import it directly so that node.js modules are resolved using the correct context.
const routesExtractorCode = await readFile(
join(__dirname, '../../utils/routes-extractor/extractor.js'),
'utf-8',
);
// Remove source map URL comments from the code if a sourcemap is present as this will not match the file.
contents.push(routesExtractorCode.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, ''));
}
return {
contents: contents.join('\n'),
loader: 'js',
resolveDir: workspaceRoot,
};
},
}),
);
if (ssrEntryPoint) {
buildOptions.plugins.push(
createVirtualModulePlugin({
namespace: ssrEntryNamespace,
loadContent: () => {
const serverEntryPoint = relative(workspaceRoot, ssrEntryPoint).replace(/\\/g, '/');
return {
contents: [
...polyfills,
`import './${serverEntryPoint}';`,
`export * from './${serverEntryPoint}';`,
].join('\n'),
loader: 'js',
resolveDir: workspaceRoot,
};
},
}),
);
}
return buildOptions;
}
function getEsBuildCommonOptions(options: NormalizedApplicationBuildOptions): BuildOptions {
const {
workspaceRoot,
outExtension,
optimizationOptions,
sourcemapOptions,
tsconfig,
externalDependencies,
outputNames,
preserveSymlinks,
jit,
} = 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 (options.i18nOptions.shouldInline) {
// Update file hashes to include translation file content
const i18nHash = Object.values(options.i18nOptions.locales).reduce(
(data, locale) => data + locale.files.map((file) => file.integrity || '').join('|'),
'',
);
footer = { js: `/**i18n:${createHash('sha256').update(i18nHash).digest('hex')}*/` };
}
return {
absWorkingDir: workspaceRoot,
bundle: true,
format: 'esm',
assetNames: outputNames.media,
conditions: ['es2020', 'es2015', 'module'],
resolveExtensions: ['.ts', '.tsx', '.mjs', '.js'],
metafile: true,
legalComments: options.extractLicenses ? 'none' : 'eof',
logLevel: options.verbose ? '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),
splitting: true,
chunkNames: options.namedChunks ? '[name]-[hash]' : 'chunk-[hash]',
tsconfig,
external: externalDependencies,
write: false,
preserveSymlinks,
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',
},
footer,
};
}