forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute-build.ts
More file actions
330 lines (292 loc) · 11.4 KB
/
execute-build.ts
File metadata and controls
330 lines (292 loc) · 11.4 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
/**
* @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 { BuilderContext } from '@angular-devkit/architect';
import { createAngularCompilation } from '../../tools/angular/compilation';
import { SourceFileCache } from '../../tools/esbuild/angular/source-file-cache';
import { generateBudgetStats } from '../../tools/esbuild/budget-stats';
import {
BuildOutputFileType,
BundleContextResult,
BundlerContext,
} from '../../tools/esbuild/bundler-context';
import { ExecutionResult, RebuildState } from '../../tools/esbuild/bundler-execution-result';
import { checkCommonJSModules } from '../../tools/esbuild/commonjs-checker';
import { extractLicenses } from '../../tools/esbuild/license-extractor';
import { profileAsync } from '../../tools/esbuild/profiling';
import {
calculateEstimatedTransferSizes,
logBuildStats,
transformSupportedBrowsersToTargets,
} from '../../tools/esbuild/utils';
import { BudgetCalculatorResult, checkBudgets } from '../../utils/bundle-calculator';
import { shouldOptimizeChunks } from '../../utils/environment-options';
import { resolveAssets } from '../../utils/resolve-assets';
import {
SERVER_APP_ENGINE_MANIFEST_FILENAME,
generateAngularServerAppEngineManifest,
} from '../../utils/server-rendering/manifest';
import { getSupportedBrowsers } from '../../utils/supported-browsers';
import { executePostBundleSteps } from './execute-post-bundle';
import { inlineI18n, loadActiveTranslations } from './i18n';
import { NormalizedApplicationBuildOptions } from './options';
import { createComponentStyleBundler, setupBundlerContexts } from './setup-bundling';
// eslint-disable-next-line max-lines-per-function
export async function executeBuild(
options: NormalizedApplicationBuildOptions,
context: BuilderContext,
rebuildState?: RebuildState,
): Promise<ExecutionResult> {
const {
projectRoot,
workspaceRoot,
i18nOptions,
optimizationOptions,
assets,
cacheOptions,
serverEntryPoint,
baseHref,
ssrOptions,
verbose,
colors,
jsonLogs,
security,
} = options;
// TODO: Consider integrating into watch mode. Would require full rebuild on target changes.
const browsers = getSupportedBrowsers(projectRoot, context.logger);
// Load active translations if inlining
// TODO: Integrate into watch mode and only load changed translations
if (i18nOptions.shouldInline) {
await loadActiveTranslations(context, i18nOptions);
}
// Reuse rebuild state or create new bundle contexts for code and global stylesheets
let bundlerContexts;
let componentStyleBundler;
let codeBundleCache;
let bundlingResult: BundleContextResult;
let templateUpdates: Map<string, string> | undefined;
if (rebuildState) {
bundlerContexts = rebuildState.rebuildContexts;
componentStyleBundler = rebuildState.componentStyleBundler;
codeBundleCache = rebuildState.codeBundleCache;
templateUpdates = rebuildState.templateUpdates;
// Reset template updates for new rebuild
templateUpdates?.clear();
const allFileChanges = rebuildState.fileChanges.all;
// Bundle all contexts that do not require TypeScript changed file checks.
// These will automatically use cached results based on the changed files.
bundlingResult = await BundlerContext.bundleAll(bundlerContexts.otherContexts, allFileChanges);
// Check the TypeScript code bundling cache for changes. If invalid, force a rebundle of
// all TypeScript related contexts.
const forceTypeScriptRebuild = codeBundleCache?.invalidate(allFileChanges);
const typescriptResults: BundleContextResult[] = [];
for (const typescriptContext of bundlerContexts.typescriptContexts) {
typescriptContext.invalidate(allFileChanges);
const result = await typescriptContext.bundle(forceTypeScriptRebuild);
typescriptResults.push(result);
}
bundlingResult = BundlerContext.mergeResults([bundlingResult, ...typescriptResults]);
} else {
const target = transformSupportedBrowsersToTargets(browsers);
codeBundleCache = new SourceFileCache(cacheOptions.enabled ? cacheOptions.path : undefined);
componentStyleBundler = createComponentStyleBundler(options, target);
if (options.templateUpdates) {
templateUpdates = new Map<string, string>();
}
bundlerContexts = setupBundlerContexts(
options,
target,
codeBundleCache,
componentStyleBundler,
// Create new reusable compilation for the appropriate mode based on the `jit` plugin option
await createAngularCompilation(!!options.jit, !options.serverEntryPoint),
templateUpdates,
);
// Bundle everything on initial build
bundlingResult = await BundlerContext.bundleAll([
...bundlerContexts.typescriptContexts,
...bundlerContexts.otherContexts,
]);
}
// Update any external component styles if enabled and rebuilding.
// TODO: Only attempt rebundling of invalidated styles once incremental build results are supported.
if (rebuildState && options.externalRuntimeStyles) {
componentStyleBundler.invalidate(rebuildState.fileChanges.all);
const componentResults = await componentStyleBundler.bundleAllFiles(true, true);
bundlingResult = BundlerContext.mergeResults([bundlingResult, ...componentResults]);
}
if (options.optimizationOptions.scripts && shouldOptimizeChunks) {
const { optimizeChunks } = await import('./chunk-optimizer');
bundlingResult = await profileAsync('OPTIMIZE_CHUNKS', () =>
optimizeChunks(
bundlingResult,
options.sourcemapOptions.scripts ? !options.sourcemapOptions.hidden || 'hidden' : false,
),
);
}
const executionResult = new ExecutionResult(
bundlerContexts,
componentStyleBundler,
codeBundleCache,
templateUpdates,
);
executionResult.addWarnings(bundlingResult.warnings);
// Add used external component style referenced files to be watched
if (options.externalRuntimeStyles) {
executionResult.extraWatchFiles.push(...componentStyleBundler.collectReferencedFiles());
}
// Return if the bundling has errors
if (bundlingResult.errors) {
executionResult.addErrors(bundlingResult.errors);
return executionResult;
}
// Analyze external imports if external options are enabled
if (options.externalPackages || bundlingResult.externalConfiguration) {
const {
externalConfiguration = [],
externalImports: { browser = [], server = [] },
} = bundlingResult;
// Similar to esbuild, --external:@foo/bar automatically implies --external:@foo/bar/*,
// which matches import paths like @foo/bar/baz.
// This means all paths within the @foo/bar package are also marked as external.
const exclusionsPrefixes = externalConfiguration.map((exclusion) => exclusion + '/');
const exclusions = new Set(externalConfiguration);
const explicitExternal = new Set<string>();
const isExplicitExternal = (dep: string): boolean => {
if (exclusions.has(dep)) {
return true;
}
for (const prefix of exclusionsPrefixes) {
if (dep.startsWith(prefix)) {
return true;
}
}
return false;
};
const implicitBrowser: string[] = [];
for (const dep of browser) {
if (isExplicitExternal(dep)) {
explicitExternal.add(dep);
} else {
implicitBrowser.push(dep);
}
}
const implicitServer: string[] = [];
for (const dep of server) {
if (isExplicitExternal(dep)) {
explicitExternal.add(dep);
} else {
implicitServer.push(dep);
}
}
executionResult.setExternalMetadata(implicitBrowser, implicitServer, [...explicitExternal]);
}
const { metafile, initialFiles, outputFiles } = bundlingResult;
executionResult.outputFiles.push(...outputFiles);
// Analyze files for bundle budget failures if present
let budgetFailures: BudgetCalculatorResult[] | undefined;
if (options.budgets) {
const compatStats = generateBudgetStats(metafile, outputFiles, initialFiles);
budgetFailures = [...checkBudgets(options.budgets, compatStats, true)];
for (const { message, severity } of budgetFailures) {
if (severity === 'error') {
executionResult.addError(message);
} else {
executionResult.addWarning(message);
}
}
}
// Calculate estimated transfer size if scripts are optimized
let estimatedTransferSizes;
if (optimizationOptions.scripts || optimizationOptions.styles.minify) {
estimatedTransferSizes = await calculateEstimatedTransferSizes(executionResult.outputFiles);
}
// Check metafile for CommonJS module usage if optimizing scripts
if (optimizationOptions.scripts) {
const messages = checkCommonJSModules(metafile, options.allowedCommonJsDependencies);
executionResult.addWarnings(messages);
}
// Copy assets
if (assets) {
executionResult.addAssets(await resolveAssets(assets, workspaceRoot));
}
// Extract and write licenses for used packages
if (options.extractLicenses) {
executionResult.addOutputFile(
'3rdpartylicenses.txt',
await extractLicenses(metafile, workspaceRoot),
BuildOutputFileType.Root,
);
}
// Watch input index HTML file if configured
if (options.indexHtmlOptions) {
executionResult.extraWatchFiles.push(options.indexHtmlOptions.input);
executionResult.htmlIndexPath = options.indexHtmlOptions.output;
executionResult.htmlBaseHref = options.baseHref;
}
// Create server app engine manifest
if (serverEntryPoint) {
executionResult.addOutputFile(
SERVER_APP_ENGINE_MANIFEST_FILENAME,
generateAngularServerAppEngineManifest(i18nOptions, security.allowedHosts, baseHref),
BuildOutputFileType.ServerRoot,
);
}
// Perform i18n translation inlining if enabled
if (i18nOptions.shouldInline) {
const result = await inlineI18n(metafile, options, executionResult, initialFiles);
executionResult.addErrors(result.errors);
executionResult.addWarnings(result.warnings);
executionResult.addPrerenderedRoutes(result.prerenderedRoutes);
} else {
const result = await executePostBundleSteps(
metafile,
options,
executionResult.outputFiles,
executionResult.assetFiles,
initialFiles,
// Set lang attribute to the defined source locale if present
i18nOptions.hasDefinedSourceLocale ? i18nOptions.sourceLocale : undefined,
);
executionResult.addErrors(result.errors);
executionResult.addWarnings(result.warnings);
executionResult.addPrerenderedRoutes(result.prerenderedRoutes);
executionResult.outputFiles.push(...result.additionalOutputFiles);
executionResult.assetFiles.push(...result.additionalAssets);
}
executionResult.addOutputFile(
'prerendered-routes.json',
JSON.stringify({ routes: executionResult.prerenderedRoutes }, null, 2),
BuildOutputFileType.Root,
);
// Write metafile if stats option is enabled
if (options.stats) {
executionResult.addOutputFile(
'stats.json',
JSON.stringify(metafile, null, 2),
BuildOutputFileType.Root,
);
}
if (!jsonLogs) {
const changedFiles =
rebuildState && executionResult.findChangedFiles(rebuildState.previousOutputInfo);
executionResult.addLog(
logBuildStats(
metafile,
outputFiles,
initialFiles,
budgetFailures,
colors,
changedFiles,
estimatedTransferSizes,
!!ssrOptions,
verbose,
),
);
}
return executionResult;
}