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.

In the future, it is also being considered that this option will replace `appShell` and `prerendering` when server routing configuration is present.
  • Loading branch information
alan-agius4 committed Sep 5, 2024
1 parent 84e14d6 commit f90791f
Show file tree
Hide file tree
Showing 15 changed files with 260 additions and 48 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
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export async function executeBuild(
optimizationOptions,
assets,
cacheOptions,
prerenderOptions,
serverEntryPoint,
ssrOptions,
verbose,
colors,
Expand Down Expand Up @@ -183,7 +183,7 @@ export async function executeBuild(
executionResult.assetFiles.push(...result.additionalAssets);
}

if (prerenderOptions) {
if (serverEntryPoint) {
const prerenderedRoutes = executionResult.prerenderedRoutes;
executionResult.addOutputFile(
'prerendered-routes.json',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
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 Down Expand Up @@ -57,10 +58,13 @@ export async function executePostBundleSteps(
indexHtmlOptions,
optimizationOptions,
sourcemapOptions,
outputMode,
serverEntryPoint,
ssrOptions,
prerenderOptions,
appShellOptions,
workspaceRoot,
disableFullServerManifestGeneration,
verbose,
} = options;

Expand Down Expand Up @@ -97,7 +101,7 @@ export async function executePostBundleSteps(
}

// Create server manifest
if (prerenderOptions || appShellOptions || ssrOptions) {
if (serverEntryPoint) {
additionalOutputFiles.push(
createOutputFile(
SERVER_APP_MANIFEST_FILENAME,
Expand Down Expand Up @@ -155,7 +159,7 @@ export async function executePostBundleSteps(
);
}

if (ssrOptions) {
if (outputMode === OutputMode.Server && !disableFullServerManifestGeneration) {
// 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 Down
6 changes: 4 additions & 2 deletions packages/angular/build/src/builders/application/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,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
5 changes: 3 additions & 2 deletions packages/angular/build/src/builders/application/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,15 @@ 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) {
if (serverEntryPoint) {
const prerenderedRoutesLength = 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
37 changes: 37 additions & 0 deletions packages/angular/build/src/builders/application/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
Schema as ApplicationBuilderOptions,
I18NTranslation,
OutputHashing,
OutputMode,
OutputPathClass,
} from './schema';

Expand Down Expand Up @@ -79,6 +80,16 @@ interface InternalOptions {
* This is only used by the development server which currently only supports a single locale per build.
*/
forceI18nFlatOutput?: boolean;

/**
* When set to `true`, disables the generation of a full manifest with routes.
*
* This option is primarily used during development to improve performance,
* as the full manifest is generated at runtime when using the development server.
*
* @default false
*/
disableFullServerManifestGeneration?: boolean;
}

/** Full set of options for `application` builder. */
Expand Down Expand Up @@ -179,6 +190,28 @@ export async function normalizeOptions(
}
}

// Validate prerender and ssr options when using the outputMode
if (
options.outputMode === OutputMode.Server &&
(typeof options.ssr === 'boolean' || !options.ssr?.entry)
) {
throw new Error('The "ssr.entry" option is required when "outputMode" is set to "server".');
}

if (options.outputMode === OutputMode.Server && !options.server) {
throw new Error('The "server" option is required when "outputMode" is set to "server".');
}

if (
options.outputMode &&
options.prerender !== undefined &&
typeof options.prerender !== 'boolean'
) {
context.logger.warn(
'The "prerender" option must be either a boolean value or omitted when "outputMode" is specified.',
);
}

// A configuration file can exist in the project or workspace root
const searchDirectories = await generateSearchDirectories([projectRoot, workspaceRoot]);
const postcssConfiguration = await loadPostcssConfiguration(searchDirectories);
Expand Down Expand Up @@ -317,6 +350,7 @@ export async function normalizeOptions(
poll,
polyfills,
statsJson,
outputMode,
stylePreprocessorOptions,
subresourceIntegrity,
verbose,
Expand All @@ -328,6 +362,7 @@ export async function normalizeOptions(
deployUrl,
clearScreen,
define,
disableFullServerManifestGeneration = false,
} = options;

// Return all the normalized options
Expand All @@ -352,6 +387,7 @@ export async function normalizeOptions(
serverEntryPoint,
prerenderOptions,
appShellOptions,
outputMode,
ssrOptions,
verbose,
watch,
Expand Down Expand Up @@ -387,6 +423,7 @@ export async function normalizeOptions(
colors: supportColor(),
clearScreen,
define,
disableFullServerManifestGeneration,
};
}

Expand Down
5 changes: 5 additions & 0 deletions packages/angular/build/src/builders/application/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,11 @@
"type": "boolean",
"description": "Generates an application shell during build time.",
"default": false
},
"outputMode": {
"type": "string",
"description": "Defines the build output target. 'static': Generates a static site for deployment on any static hosting service. 'server': Produces an application designed for deployment on a server that supports server-side rendering (SSR).",
"enum": ["static", "server"]
}
},
"additionalProperties": false,
Expand Down
19 changes: 16 additions & 3 deletions packages/angular/build/src/builders/application/setup-bundling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
createBrowserPolyfillBundleOptions,
createServerMainCodeBundleOptions,
createServerPolyfillBundleOptions,
createSsrEntryCodeBundleOptions,
} from '../../tools/esbuild/application-code-bundle';
import { BundlerContext } from '../../tools/esbuild/bundler-context';
import { createGlobalScriptsBundleOptions } from '../../tools/esbuild/global-scripts';
Expand All @@ -36,9 +37,10 @@ export function setupBundlerContexts(
codeBundleCache: SourceFileCache,
): BundlerContext[] {
const {
outputMode,
serverEntryPoint,
appShellOptions,
prerenderOptions,
serverEntryPoint,
ssrOptions,
workspaceRoot,
watch = false,
Expand Down Expand Up @@ -90,9 +92,9 @@ export function setupBundlerContexts(
}

// Skip server build when none of the features are enabled.
if (serverEntryPoint && (prerenderOptions || appShellOptions || ssrOptions)) {
if (serverEntryPoint && (outputMode || prerenderOptions || appShellOptions || ssrOptions)) {
const nodeTargets = [...target, ...getSupportedNodeTargets()];
// Server application code

bundlerContexts.push(
new BundlerContext(
workspaceRoot,
Expand All @@ -101,6 +103,17 @@ export function setupBundlerContexts(
),
);

if (outputMode && ssrOptions?.entry) {
// New behavior introduced: 'server.ts' is now bundled separately from 'main.server.ts'.
bundlerContexts.push(
new BundlerContext(
workspaceRoot,
watch,
createSsrEntryCodeBundleOptions(options, nodeTargets, codeBundleCache),
),
);
}

// Server polyfills code
const serverPolyfillBundleOptions = createServerPolyfillBundleOptions(
options,
Expand Down
7 changes: 4 additions & 3 deletions packages/angular/build/src/builders/dev-server/vite-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,16 +93,17 @@ export async function* serveWithVite(
// This is so instead of prerendering all the routes for every change, the page is "prerendered" when it is requested.
browserOptions.prerender = false;

// Avoid bundling and processing the ssr entry-point as this is not used by the dev-server.
browserOptions.ssr = true;

// https://nodejs.org/api/process.html#processsetsourcemapsenabledval
process.setSourceMapsEnabled(true);
}

// Set all packages as external to support Vite's prebundle caching
browserOptions.externalPackages = serverOptions.prebundle;

// Disable generating a full manifest with routes.
// This is done during runtime when using the dev-server.
browserOptions.disableFullServerManifestGeneration = true;

// The development server currently only supports a single locale when localizing.
// This matches the behavior of the Webpack-based development server but could be expanded in the future.
if (
Expand Down
Loading

0 comments on commit f90791f

Please sign in to comment.