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 defines the build output target, offering two modes:
- `'static'`: Generates a static site suitable for deployment on any static hosting service. This mode can produce a fully client-side rendered (CSR) or static site generated (SSG) site. When SSG is enabled, redirects are handled using the `<meta>` tag.
- `'server'`: Produces an application designed for deployment on a server that supports server-side rendering (SSR) or a hybrid approach.

Additionally, the `outputMode` option determines whether the new API is used. If enabled, it bundles the `server.ts` as a separate entry point, preventing it from directly referencing `main.server.ts` and excluding it from localization.

This option will replace `appShell` and `prerendering` when server routing configuration is present.
  • Loading branch information
alan-agius4 committed Sep 13, 2024
1 parent ac71ce1 commit a3f50d5
Show file tree
Hide file tree
Showing 21 changed files with 522 additions and 174 deletions.
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
Server = 2,
// (undocumented)
SSRServer = 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.SSRServer,
);
}

// 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 { loadEsmModule } from '../../utils/load-esm';
import {
SERVER_APP_MANIFEST_FILENAME,
generateAngularServerAppManifest,
} from '../../utils/server-rendering/manifest';
import { prerenderPages } from '../../utils/server-rendering/prerender';
import { RoutersExtractorWorkerResult as SerializableRouteTreeNode } from '../../utils/server-rendering/routes-extractor-worker';
import { augmentAppWithServiceWorkerEsbuild } from '../../utils/service-worker';
import { INDEX_HTML_SERVER, NormalizedApplicationBuildOptions } from './options';
import { OutputMode } from './schema';

type Writeable<T extends readonly unknown[]> = T extends readonly (infer U)[] ? U[] : never;

/**
* 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 @@ -97,7 +106,7 @@ export async function executePostBundleSteps(
}

// Create server manifest
if (prerenderOptions || appShellOptions || ssrOptions) {
if (serverEntryPoint) {
additionalOutputFiles.push(
createOutputFile(
SERVER_APP_MANIFEST_FILENAME,
Expand All @@ -114,36 +123,32 @@ export async function executePostBundleSteps(

// 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 +160,24 @@ export async function executePostBundleSteps(
);
}

if (ssrOptions) {
const { RenderMode } = await loadEsmModule<typeof import('@angular/ssr')>('@angular/ssr');
const serializableRouteTreeNodeForManifest: Writeable<SerializableRouteTreeNode> = [];

for (const metadata of serializableRouteTreeNode) {
switch (metadata.renderMode) {
case RenderMode.Prerender:
prerenderedRoutes[metadata.route] = { headers: metadata.headers };
break;

case RenderMode.Server:
case RenderMode.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 +187,7 @@ export async function executePostBundleSteps(
additionalHtmlOutputFiles,
outputFiles,
optimizationOptions.styles.inlineCritical ?? false,
serializableRouteTreeNode,
serializableRouteTreeNodeForManifest,
),
);
}
Expand Down
31 changes: 20 additions & 11 deletions packages/angular/build/src/builders/application/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
import { BuilderContext } from '@angular-devkit/architect';
import { join, posix } 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.SSRServer,
),
// Updated files for each locale.
...updatedOutputFiles,
];
Expand Down
7 changes: 4 additions & 3 deletions packages/angular/build/src/builders/application/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,16 +88,16 @@ export async function* buildApplicationInternal(

yield* runEsBuildBuildAction(
async (rebuildState) => {
const { prerenderOptions, jsonLogs } = normalizedOptions;
const { serverEntryPoint, jsonLogs } = normalizedOptions;

const startTime = process.hrtime.bigint();
const result = await executeBuild(normalizedOptions, context, rebuildState);

if (jsonLogs) {
result.addLog(await createJsonBuildManifest(result, normalizedOptions));
} else {
if (prerenderOptions) {
const prerenderedRoutesLength = result.prerenderedRoutes.length;
if (serverEntryPoint) {
const prerenderedRoutesLength = Object.keys(result.prerenderedRoutes).length;
let prerenderMsg = `Prerendered ${prerenderedRoutesLength} static route`;
prerenderMsg += prerenderedRoutesLength !== 1 ? 's.' : '.';

Expand Down Expand Up @@ -236,6 +236,7 @@ export async function* buildApplication(
typeDirectory = outputOptions.browser;
break;
case BuildOutputFileType.Server:
case BuildOutputFileType.SSRServer:
typeDirectory = outputOptions.server;
break;
case BuildOutputFileType.Root:
Expand Down
Loading

0 comments on commit a3f50d5

Please sign in to comment.