Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(@angular/build): introduce outputMode option to the application builder #28355

Merged
merged 1 commit into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions goldens/circular-deps/packages.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,18 @@
[
"packages/angular/build/src/tools/esbuild/bundler-context.ts",
"packages/angular/build/src/tools/esbuild/utils.ts",
"packages/angular/build/src/tools/esbuild/bundler-execution-result.ts"
"packages/angular/build/src/utils/server-rendering/manifest.ts"
],
[
"packages/angular/build/src/tools/esbuild/bundler-context.ts",
"packages/angular/build/src/tools/esbuild/utils.ts",
"packages/angular/build/src/utils/server-rendering/manifest.ts"
"packages/angular/build/src/utils/server-rendering/manifest.ts",
"packages/angular/build/src/tools/esbuild/bundler-execution-result.ts"
],
[
"packages/angular/build/src/tools/esbuild/bundler-execution-result.ts",
"packages/angular/build/src/tools/esbuild/utils.ts"
"packages/angular/build/src/tools/esbuild/utils.ts",
"packages/angular/build/src/utils/server-rendering/manifest.ts"
],
[
"packages/angular/cli/src/analytics/analytics-collector.ts",
Expand Down
9 changes: 6 additions & 3 deletions goldens/public-api/angular/build/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export interface ApplicationBuilderOptions {
namedChunks?: boolean;
optimization?: OptimizationUnion;
outputHashing?: OutputHashing;
outputMode?: OutputMode;
outputPath: OutputPathUnion;
poll?: number;
polyfills?: string[];
Expand Down Expand Up @@ -99,13 +100,15 @@ export interface BuildOutputFile extends OutputFile {
// @public (undocumented)
export enum BuildOutputFileType {
// (undocumented)
Browser = 1,
Browser = 0,
// (undocumented)
Media = 2,
Media = 1,
// (undocumented)
Root = 4,
// (undocumented)
Server = 3
ServerApplication = 2,
// (undocumented)
ServerRoot = 3
}

// @public
Expand Down
34 changes: 32 additions & 2 deletions packages/angular/build/src/builders/application/execute-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

import { BuilderContext } from '@angular-devkit/architect';
import assert from 'node:assert';
import { SourceFileCache } from '../../tools/esbuild/angular/source-file-cache';
import { generateBudgetStats } from '../../tools/esbuild/budget-stats';
import { BuildOutputFileType, BundlerContext } from '../../tools/esbuild/bundler-context';
Expand All @@ -18,13 +19,19 @@ import { calculateEstimatedTransferSizes, logBuildStats } from '../../tools/esbu
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 { optimizeChunks } from './chunk-optimizer';
import { executePostBundleSteps } from './execute-post-bundle';
import { inlineI18n, loadActiveTranslations } from './i18n';
import { NormalizedApplicationBuildOptions } from './options';
import { OutputMode } from './schema';
import { setupBundlerContexts } from './setup-bundling';

// eslint-disable-next-line max-lines-per-function
export async function executeBuild(
options: NormalizedApplicationBuildOptions,
context: BuilderContext,
Expand All @@ -36,8 +43,10 @@ export async function executeBuild(
i18nOptions,
optimizationOptions,
assets,
outputMode,
cacheOptions,
prerenderOptions,
serverEntryPoint,
baseHref,
ssrOptions,
verbose,
colors,
Expand Down Expand Up @@ -160,6 +169,15 @@ export async function executeBuild(
executionResult.htmlBaseHref = options.baseHref;
}

// Create server app engine manifest
if (serverEntryPoint) {
executionResult.addOutputFile(
SERVER_APP_ENGINE_MANIFEST_FILENAME,
generateAngularServerAppEngineManifest(i18nOptions, baseHref, undefined),
BuildOutputFileType.ServerRoot,
);
}

// Perform i18n translation inlining if enabled
if (i18nOptions.shouldInline) {
const result = await inlineI18n(options, executionResult, initialFiles);
Expand All @@ -183,8 +201,20 @@ export async function executeBuild(
executionResult.assetFiles.push(...result.additionalAssets);
}

if (prerenderOptions) {
if (serverEntryPoint) {
const prerenderedRoutes = executionResult.prerenderedRoutes;

// Regenerate the manifest to append prerendered routes data. This is only needed if SSR is enabled.
if (outputMode === OutputMode.Server && Object.keys(prerenderedRoutes).length) {
const manifest = executionResult.outputFiles.find(
(f) => f.path === SERVER_APP_ENGINE_MANIFEST_FILENAME,
);
assert(manifest, `${SERVER_APP_ENGINE_MANIFEST_FILENAME} was not found in output files.`);
manifest.contents = new TextEncoder().encode(
generateAngularServerAppEngineManifest(i18nOptions, baseHref, prerenderedRoutes),
);
}

executionResult.addOutputFile(
'prerendered-routes.json',
JSON.stringify({ routes: prerenderedRoutes }, null, 2),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,25 @@ import {
BuildOutputFileType,
InitialFileRecord,
} from '../../tools/esbuild/bundler-context';
import { BuildOutputAsset } from '../../tools/esbuild/bundler-execution-result';
import {
BuildOutputAsset,
PrerenderedRoutesRecord,
} from '../../tools/esbuild/bundler-execution-result';
import { generateIndexHtml } from '../../tools/esbuild/index-html-generator';
import { createOutputFile } from '../../tools/esbuild/utils';
import { maxWorkers } from '../../utils/environment-options';
import {
SERVER_APP_MANIFEST_FILENAME,
generateAngularServerAppManifest,
} from '../../utils/server-rendering/manifest';
import {
RouteRenderMode,
WritableSerializableRouteTreeNode,
} from '../../utils/server-rendering/models';
import { prerenderPages } from '../../utils/server-rendering/prerender';
import { augmentAppWithServiceWorkerEsbuild } from '../../utils/service-worker';
import { INDEX_HTML_SERVER, NormalizedApplicationBuildOptions } from './options';
import { OutputMode } from './schema';

/**
* Run additional builds steps including SSG, AppShell, Index HTML file and Service worker generation.
Expand All @@ -43,25 +51,26 @@ export async function executePostBundleSteps(
warnings: string[];
additionalOutputFiles: BuildOutputFile[];
additionalAssets: BuildOutputAsset[];
prerenderedRoutes: string[];
prerenderedRoutes: PrerenderedRoutesRecord;
}> {
const additionalAssets: BuildOutputAsset[] = [];
const additionalOutputFiles: BuildOutputFile[] = [];
const allErrors: string[] = [];
const allWarnings: string[] = [];
const prerenderedRoutes: string[] = [];
const prerenderedRoutes: PrerenderedRoutesRecord = {};

const {
baseHref = '/',
serviceWorker,
indexHtmlOptions,
optimizationOptions,
sourcemapOptions,
ssrOptions,
outputMode,
serverEntryPoint,
prerenderOptions,
appShellOptions,
workspaceRoot,
verbose,
disableFullServerManifestGeneration,
} = options;

// Index HTML content without CSS inlining to be used for server rendering (AppShell, SSG and SSR).
Expand Down Expand Up @@ -91,13 +100,13 @@ export async function executePostBundleSteps(
if (ssrContent) {
additionalHtmlOutputFiles.set(
INDEX_HTML_SERVER,
createOutputFile(INDEX_HTML_SERVER, ssrContent, BuildOutputFileType.Server),
createOutputFile(INDEX_HTML_SERVER, ssrContent, BuildOutputFileType.ServerApplication),
);
}
}

// Create server manifest
if (prerenderOptions || appShellOptions || ssrOptions) {
if (serverEntryPoint) {
additionalOutputFiles.push(
createOutputFile(
SERVER_APP_MANIFEST_FILENAME,
Expand All @@ -106,44 +115,41 @@ export async function executePostBundleSteps(
outputFiles,
optimizationOptions.styles.inlineCritical ?? false,
undefined,
locale,
),
BuildOutputFileType.Server,
BuildOutputFileType.ServerApplication,
),
);
}

// Pre-render (SSG) and App-shell
// If localization is enabled, prerendering is handled in the inlining process.
if ((prerenderOptions || appShellOptions) && !allErrors.length) {
if (
!disableFullServerManifestGeneration &&
(prerenderOptions || appShellOptions || (outputMode && serverEntryPoint)) &&
!allErrors.length
) {
assert(
indexHtmlOptions,
'The "index" option is required when using the "ssg" or "appShell" options.',
);

const {
output,
warnings,
errors,
prerenderedRoutes: generatedRoutes,
serializableRouteTreeNode,
} = await prerenderPages(
const { output, warnings, errors, serializableRouteTreeNode } = await prerenderPages(
workspaceRoot,
baseHref,
appShellOptions,
prerenderOptions,
[...outputFiles, ...additionalOutputFiles],
assetFiles,
outputMode,
sourcemapOptions.scripts,
maxWorkers,
verbose,
);

allErrors.push(...errors);
allWarnings.push(...warnings);
prerenderedRoutes.push(...Array.from(generatedRoutes));

const indexHasBeenPrerendered = generatedRoutes.has(indexHtmlOptions.output);

const indexHasBeenPrerendered = output[indexHtmlOptions.output];
for (const [path, { content, appShellRoute }] of Object.entries(output)) {
// Update the index contents with the app shell under these conditions:
// - Replace 'index.html' with the app shell only if it hasn't been prerendered yet.
Expand All @@ -155,7 +161,26 @@ export async function executePostBundleSteps(
);
}

if (ssrOptions) {
const serializableRouteTreeNodeForManifest: WritableSerializableRouteTreeNode = [];

for (const metadata of serializableRouteTreeNode) {
switch (metadata.renderMode) {
case RouteRenderMode.Prerender:
case /* Legacy building mode */ undefined: {
if (!metadata.redirectTo || outputMode === OutputMode.Static) {
prerenderedRoutes[metadata.route] = { headers: metadata.headers };
}
break;
}
case RouteRenderMode.Server:
case RouteRenderMode.Client:
serializableRouteTreeNodeForManifest.push(metadata);

break;
}
}

if (outputMode === OutputMode.Server) {
// Regenerate the manifest to append route tree. This is only needed if SSR is enabled.
const manifest = additionalOutputFiles.find((f) => f.path === SERVER_APP_MANIFEST_FILENAME);
assert(manifest, `${SERVER_APP_MANIFEST_FILENAME} was not found in output files.`);
Expand All @@ -165,7 +190,8 @@ export async function executePostBundleSteps(
additionalHtmlOutputFiles,
outputFiles,
optimizationOptions.styles.inlineCritical ?? false,
serializableRouteTreeNode,
serializableRouteTreeNodeForManifest,
locale,
),
);
}
Expand Down
33 changes: 21 additions & 12 deletions packages/angular/build/src/builders/application/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@
*/

import { BuilderContext } from '@angular-devkit/architect';
import { join, posix } from 'node:path';
import { join } from 'node:path';
import { BuildOutputFileType, InitialFileRecord } from '../../tools/esbuild/bundler-context';
import { ExecutionResult } from '../../tools/esbuild/bundler-execution-result';
import {
ExecutionResult,
PrerenderedRoutesRecord,
} from '../../tools/esbuild/bundler-execution-result';
import { I18nInliner } from '../../tools/esbuild/i18n-inliner';
import { maxWorkers } from '../../utils/environment-options';
import { loadTranslations } from '../../utils/i18n-options';
Expand All @@ -28,7 +31,11 @@ export async function inlineI18n(
options: NormalizedApplicationBuildOptions,
executionResult: ExecutionResult,
initialFiles: Map<string, InitialFileRecord>,
): Promise<{ errors: string[]; warnings: string[]; prerenderedRoutes: string[] }> {
): Promise<{
errors: string[];
warnings: string[];
prerenderedRoutes: PrerenderedRoutesRecord;
}> {
// Create the multi-threaded inliner with common options and the files generated from the build.
const inliner = new I18nInliner(
{
Expand All @@ -39,10 +46,14 @@ export async function inlineI18n(
maxWorkers,
);

const inlineResult: { errors: string[]; warnings: string[]; prerenderedRoutes: string[] } = {
const inlineResult: {
errors: string[];
warnings: string[];
prerenderedRoutes: PrerenderedRoutesRecord;
} = {
errors: [],
warnings: [],
prerenderedRoutes: [],
prerenderedRoutes: {},
};

// For each active locale, use the inliner to process the output files of the build.
Expand Down Expand Up @@ -95,15 +106,11 @@ export async function inlineI18n(
destination: join(locale, assetFile.destination),
});
}

inlineResult.prerenderedRoutes.push(
...generatedRoutes.map((route) => posix.join('/', locale, route)),
);
} else {
inlineResult.prerenderedRoutes.push(...generatedRoutes);
executionResult.assetFiles.push(...additionalAssets);
}

inlineResult.prerenderedRoutes = { ...inlineResult.prerenderedRoutes, ...generatedRoutes };
updatedOutputFiles.push(...localeOutputFiles);
}
} finally {
Expand All @@ -112,8 +119,10 @@ export async function inlineI18n(

// Update the result with all localized files.
executionResult.outputFiles = [
// Root files are not modified.
...executionResult.outputFiles.filter(({ type }) => type === BuildOutputFileType.Root),
// Root and SSR entry files are not modified.
...executionResult.outputFiles.filter(
({ type }) => type === BuildOutputFileType.Root || type === BuildOutputFileType.ServerRoot,
),
// Updated files for each locale.
...updatedOutputFiles,
];
Expand Down
Loading