Skip to content

Commit

Permalink
feat(@angular/build): introduce outputMode option to the applicatio…
Browse files Browse the repository at this point in the history
…n builder

The `outputMode` option accepts two values:
- **`static`:**  Generates a static output (HTML, CSS, JavaScript) suitable for deployment on static hosting services or CDNs. This mode supports both client-side rendering (CSR) and static site generation (SSG).
- **`server`:** Generates a server bundle in addition to static assets, enabling server-side rendering (SSR) and hybrid rendering strategies. This output is intended for deployment on a Node.js server or serverless environment.

- **Replaces `appShell` and `prerender`:**  The `outputMode` option simplifies the CLI by replacing the `appShell` and `prerender` options when server-side routing is configured.
- **Controls Server API Usage:**  `outputMode` determines whether the new server API is utilized. In `server` mode, `server.ts` is bundled as a separate entry point, preventing direct references to `main.server.ts` and excluding it from localization.

Closes #27356, closes #27403, closes #25726, closes #25718 and closes #27196
  • Loading branch information
alan-agius4 committed Sep 19, 2024
1 parent 8723e0c commit 3b00fc9
Show file tree
Hide file tree
Showing 38 changed files with 1,343 additions and 268 deletions.
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

0 comments on commit 3b00fc9

Please sign in to comment.