Skip to content

Commit

Permalink
refactor(@angular/build): integrate template update function generati…
Browse files Browse the repository at this point in the history
…on with builder results

When using the development server with the application builder (default for new projects),
experimental support for component template hot replacement is now available for use. To
enable support, the `NG_HMR_TEMPLATES=1` environment variable must present when executing
the development server (for example, `NG_HMR_TEMPLATES=1 ng serve`). Once support has become
stable, template hot replacement will be enabled by default.
  • Loading branch information
clydin authored and alan-agius4 committed Nov 5, 2024
1 parent bcb24b9 commit ae9dfdd
Show file tree
Hide file tree
Showing 8 changed files with 60 additions and 10 deletions.
17 changes: 16 additions & 1 deletion packages/angular/build/src/builders/application/build-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { logMessages, withNoProgress, withSpinner } from '../../tools/esbuild/ut
import { shouldWatchRoot } from '../../utils/environment-options';
import { NormalizedCachedOptions } from '../../utils/normalize-cache';
import { NormalizedApplicationBuildOptions, NormalizedOutputOptions } from './options';
import { FullResult, Result, ResultKind, ResultMessage } from './results';
import { ComponentUpdateResult, FullResult, Result, ResultKind, ResultMessage } from './results';

// Watch workspace for package manager changes
const packageWatchFiles = [
Expand Down Expand Up @@ -207,6 +207,7 @@ async function emitOutputResult(
externalMetadata,
htmlIndexPath,
htmlBaseHref,
templateUpdates,
}: ExecutionResult,
outputOptions: NormalizedApplicationBuildOptions['outputOptions'],
): Promise<Result> {
Expand All @@ -221,6 +222,20 @@ async function emitOutputResult(
};
}

// Template updates only exist if no other changes have occurred
if (templateUpdates?.size) {
const updateResult: ComponentUpdateResult = {
kind: ResultKind.ComponentUpdate,
updates: Array.from(templateUpdates).map(([id, content]) => ({
type: 'template',
id,
content,
})),
};

return updateResult;
}

const result: FullResult = {
kind: ResultKind.Full,
warnings: warnings as ResultMessage[],
Expand Down
19 changes: 16 additions & 3 deletions packages/angular/build/src/builders/application/execute-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ export async function executeBuild(
i18nOptions,
optimizationOptions,
assets,
outputMode,
cacheOptions,
serverEntryPoint,
baseHref,
Expand All @@ -73,10 +72,15 @@ export async function executeBuild(
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.
Expand All @@ -85,7 +89,6 @@ export async function executeBuild(

// Check the TypeScript code bundling cache for changes. If invalid, force a rebundle of
// all TypeScript related contexts.
// TODO: Enable cached bundling for the typescript contexts
const forceTypeScriptRebuild = codeBundleCache?.invalidate(allFileChanges);
const typescriptResults: BundleContextResult[] = [];
for (const typescriptContext of bundlerContexts.typescriptContexts) {
Expand All @@ -98,7 +101,16 @@ export async function executeBuild(
const target = transformSupportedBrowsersToTargets(browsers);
codeBundleCache = new SourceFileCache(cacheOptions.enabled ? cacheOptions.path : undefined);
componentStyleBundler = createComponentStyleBundler(options, target);
bundlerContexts = setupBundlerContexts(options, target, codeBundleCache, componentStyleBundler);
if (options.templateUpdates) {
templateUpdates = new Map<string, string>();
}
bundlerContexts = setupBundlerContexts(
options,
target,
codeBundleCache,
componentStyleBundler,
templateUpdates,
);

// Bundle everything on initial build
bundlingResult = await BundlerContext.bundleAll([
Expand Down Expand Up @@ -129,6 +141,7 @@ export async function executeBuild(
bundlerContexts,
componentStyleBundler,
codeBundleCache,
templateUpdates,
);
executionResult.addWarnings(bundlingResult.warnings);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export function setupBundlerContexts(
target: string[],
codeBundleCache: SourceFileCache,
stylesheetBundler: ComponentStylesheetBundler,
templateUpdates: Map<string, string> | undefined,
): {
typescriptContexts: BundlerContext[];
otherContexts: BundlerContext[];
Expand All @@ -55,7 +56,13 @@ export function setupBundlerContexts(
new BundlerContext(
workspaceRoot,
watch,
createBrowserCodeBundleOptions(options, target, codeBundleCache, stylesheetBundler),
createBrowserCodeBundleOptions(
options,
target,
codeBundleCache,
stylesheetBundler,
templateUpdates,
),
),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export interface CompilerPluginOptions {
incremental: boolean;
externalRuntimeStyles?: boolean;
instrumentForCoverage?: (request: string) => boolean;
templateUpdates?: boolean;
templateUpdates?: Map<string, string>;
}

// eslint-disable-next-line max-lines-per-function
Expand Down Expand Up @@ -303,6 +303,12 @@ export function createCompilerPlugin(
!!initializationResult.compilerOptions.inlineSourceMap;
referencedFiles = initializationResult.referencedFiles;
externalStylesheets = initializationResult.externalStylesheets;
if (initializationResult.templateUpdates) {
// Propagate any template updates
initializationResult.templateUpdates.forEach((value, key) =>
pluginOptions.templateUpdates?.set(key, value),
);
}
} catch (error) {
(result.errors ??= []).push({
text: 'Angular compilation initialization failed.',
Expand Down Expand Up @@ -657,7 +663,7 @@ function createCompilerOptionsTransformer(
sourceRoot: undefined,
preserveSymlinks,
externalRuntimeStyles: pluginOptions.externalRuntimeStyles,
_enableHmr: pluginOptions.templateUpdates,
_enableHmr: !!pluginOptions.templateUpdates,
};
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,17 @@ export function createBrowserCodeBundleOptions(
target: string[],
sourceFileCache: SourceFileCache,
stylesheetBundler: ComponentStylesheetBundler,
templateUpdates: Map<string, string> | undefined,
): BundlerOptionsFactory {
return (loadCache) => {
const { entryPoints, outputNames, polyfills } = options;

const pluginOptions = createCompilerPluginOptions(options, sourceFileCache, loadCache);
const pluginOptions = createCompilerPluginOptions(
options,
sourceFileCache,
loadCache,
templateUpdates,
);

const zoneless = isZonelessApp(polyfills);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export interface RebuildState {
codeBundleCache?: SourceFileCache;
fileChanges: ChangedFiles;
previousOutputHashes: Map<string, string>;
templateUpdates?: Map<string, string>;
}

export interface ExternalResultMetadata {
Expand Down Expand Up @@ -60,6 +61,7 @@ export class ExecutionResult {
},
private componentStyleBundler: ComponentStylesheetBundler,
private codeBundleCache?: SourceFileCache,
readonly templateUpdates?: Map<string, string>,
) {}

addOutputFile(path: string, content: string | Uint8Array, type: BuildOutputFileType): void {
Expand Down Expand Up @@ -166,6 +168,7 @@ export class ExecutionResult {
componentStyleBundler: this.componentStyleBundler,
fileChanges,
previousOutputHashes: new Map(this.outputFiles.map((file) => [file.path, file.hash])),
templateUpdates: this.templateUpdates,
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export function createCompilerPluginOptions(
options: NormalizedApplicationBuildOptions,
sourceFileCache: SourceFileCache,
loadResultCache?: LoadResultCache,
templateUpdates?: Map<string, string>,
): CreateCompilerPluginParameters[0] {
const {
sourcemapOptions,
Expand All @@ -26,7 +27,6 @@ export function createCompilerPluginOptions(
jit,
externalRuntimeStyles,
instrumentForCoverage,
templateUpdates,
} = options;
const incremental = !!options.watch;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function createAngularComponentMiddleware(
return;
}

const updateCode = templateUpdates.get(componentId) ?? '';
const updateCode = templateUpdates.get(encodeURIComponent(componentId)) ?? '';

res.setHeader('Content-Type', 'text/javascript');
res.setHeader('Cache-Control', 'no-cache');
Expand Down

0 comments on commit ae9dfdd

Please sign in to comment.