Skip to content

Commit b0358d8

Browse files
d.weizheclaude
andcommitted
feat(@angular/build): add manualRebuild option to the dev-server
When `manualRebuild` is enabled, the development server keeps tracking file changes but no longer rebuilds automatically on every change. Instead, all pending changes are accumulated and rebuilt incrementally (reusing the in-memory build state) only when a rebuild is explicitly requested, either by sending a `POST` request to the `/__ng_rebuild` endpoint or by pressing `b` in the terminal. The endpoint responds once the rebuild has completed with a JSON object containing the outcome (`success`, `failure`, `no-changes` or `cancelled`). Cross-origin browser requests to the endpoint are rejected. This is useful when many files are edited in a batch (for example by AI coding agents) to avoid repeated intermediate rebuilds without having to restart the development server and lose the incremental build state. Closes angular/angular#72079 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4a3b91a commit b0358d8

12 files changed

Lines changed: 679 additions & 17 deletions

File tree

‎goldens/public-api/angular/build/index.api.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ export type DevServerBuilderOptions = {
122122
host?: string;
123123
inspect?: Inspect;
124124
liveReload?: boolean;
125+
manualRebuild?: boolean;
125126
open?: boolean;
126127
poll?: number;
127128
port?: number;

‎packages/angular/build/src/builders/application/build-action.ts‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
} from '../../tools/esbuild/stylesheets/sass-language';
2020
import { logMessages, withNoProgress, withSpinner } from '../../tools/esbuild/utils';
2121
import { initializeHash } from '../../utils/hash';
22+
import type { ManualRebuildController, ManualRebuildResult } from '../../utils/manual-rebuild';
2223
import { NormalizedCachedOptions } from '../../utils/normalize-cache';
2324
import { ChangedFiles } from '../../utils/watcher';
2425
import { NormalizedApplicationBuildOptions, NormalizedOutputOptions } from './options';
@@ -50,6 +51,7 @@ export async function* runEsBuildBuildAction(
5051
colors?: boolean;
5152
jsonLogs?: boolean;
5253
incrementalResults?: boolean;
54+
manualRebuild?: ManualRebuildController;
5355
},
5456
): AsyncIterable<Result> {
5557
const {
@@ -67,6 +69,7 @@ export async function* runEsBuildBuildAction(
6769
colors,
6870
jsonLogs,
6971
incrementalResults,
72+
manualRebuild,
7073
} = options;
7174

7275
await initializeHash();
@@ -95,6 +98,11 @@ export async function* runEsBuildBuildAction(
9598
if (watch) {
9699
if (progress) {
97100
logger.info('Watch mode enabled. Watching for file changes...');
101+
if (manualRebuild) {
102+
logger.info(
103+
'Manual rebuild mode enabled. File changes will be rebuilt only when a rebuild is requested.',
104+
);
105+
}
98106
}
99107

100108
// Setup a watcher
@@ -140,8 +148,25 @@ export async function* runEsBuildBuildAction(
140148

141149
// Wait for changes and rebuild as needed
142150
const currentWatchFiles = new Set(result.watchFiles);
151+
let rebuilds: AsyncIterable<{
152+
changes: ChangedFiles;
153+
requests?: ((result: ManualRebuildResult) => void)[];
154+
}>;
155+
if (manualRebuild) {
156+
const { waitForManualRebuilds } = await import('../../utils/manual-rebuild');
157+
rebuilds = waitForManualRebuilds(watcher, manualRebuild, {
158+
onChangesPending: () => {
159+
if (progress) {
160+
logger.info('File changes detected. Waiting for a rebuild request...');
161+
}
162+
},
163+
});
164+
} else {
165+
rebuilds = mapChanges(watcher);
166+
}
167+
143168
try {
144-
for await (const changes of watcher) {
169+
for await (const { changes, requests } of rebuilds) {
145170
if (options.signal?.aborted) {
146171
break;
147172
}
@@ -202,15 +227,33 @@ export async function* runEsBuildBuildAction(
202227

203228
// Clear initial build errors flag if no errors are now present
204229
hasInitialErrors &&= result.errors.length > 0;
230+
231+
// Notify any manual rebuild requesters now that all results have been emitted
232+
if (requests?.length) {
233+
const status = result.errors.length > 0 ? 'failure' : 'success';
234+
for (const resolve of requests) {
235+
resolve({ status });
236+
}
237+
}
205238
}
206239
} finally {
240+
manualRebuild?.close();
241+
207242
// Stop the watcher and cleanup incremental rebuild state
208243
await Promise.allSettled([watcher.close(), result.dispose()]);
209244

210245
shutdownSassWorkerPool();
211246
}
212247
}
213248

249+
async function* mapChanges(
250+
watcher: AsyncIterable<ChangedFiles>,
251+
): AsyncIterable<{ changes: ChangedFiles }> {
252+
for await (const changes of watcher) {
253+
yield { changes };
254+
}
255+
}
256+
214257
function* emitOutputResults(
215258
{
216259
outputFiles,

‎packages/angular/build/src/builders/application/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ export async function* buildApplicationInternal(
137137
colors: normalizedOptions.colors,
138138
jsonLogs: normalizedOptions.jsonLogs,
139139
incrementalResults: normalizedOptions.incrementalResults,
140+
manualRebuild: normalizedOptions.manualRebuild,
140141
logger,
141142
signal,
142143
},

‎packages/angular/build/src/builders/application/options.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { supportColor } from '../../utils/color';
1515
import { useJSONBuildLogs, usePartialSsrBuild } from '../../utils/environment-options';
1616
import { I18nOptions, createI18nOptions } from '../../utils/i18n-options';
1717
import { IndexHtmlTransform } from '../../utils/index-file/index-html-generator';
18+
import type { ManualRebuildController } from '../../utils/manual-rebuild';
1819
import { normalizeCacheOptions } from '../../utils/normalize-cache';
1920
import { canonicalizePath } from '../../utils/path';
2021
import {
@@ -114,6 +115,13 @@ interface InternalOptions {
114115
*/
115116
incrementalResults?: boolean;
116117

118+
/**
119+
* When provided, file changes detected in watch mode do not automatically trigger a rebuild.
120+
* Instead, accumulated changes are rebuilt incrementally only when a rebuild is requested
121+
* via the controller. This option also requires watch to be enabled to have an effect.
122+
*/
123+
manualRebuild?: ManualRebuildController;
124+
117125
/**
118126
* Enables instrumentation to collect code coverage data for specific files.
119127
*
@@ -560,6 +568,7 @@ export async function normalizeOptions(
560568
security,
561569
templateUpdates: !!options.templateUpdates,
562570
incrementalResults: !!options.incrementalResults,
571+
manualRebuild: options.manualRebuild,
563572
customConditions: options.conditions,
564573
frameworkVersion: await findFrameworkVersion(projectRoot),
565574
};

‎packages/angular/build/src/builders/dev-server/options.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@ import { Schema as DevServerOptions } from './schema';
1515

1616
export type NormalizedDevServerOptions = Omit<
1717
Awaited<ReturnType<typeof normalizeOptions>>,
18-
'strictPort'
18+
'strictPort' | 'manualRebuild'
1919
> & {
2020
strictPort?: boolean;
21+
manualRebuild?: boolean;
2122
};
2223

2324
/**
@@ -115,6 +116,7 @@ export async function normalizeOptions(
115116
verbose,
116117
define,
117118
watch,
119+
manualRebuild,
118120
liveReload,
119121
hmr,
120122
headers,
@@ -138,6 +140,7 @@ export async function normalizeOptions(
138140
verbose,
139141
define,
140142
watch,
143+
manualRebuild: !!manualRebuild,
141144
liveReload: !!liveReload,
142145
hmr: hmr ?? !!liveReload,
143146
headers,

‎packages/angular/build/src/builders/dev-server/schema.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,11 @@
102102
"type": "number",
103103
"description": "Enable and define the file watching poll time period in milliseconds."
104104
},
105+
"manualRebuild": {
106+
"type": "boolean",
107+
"description": "Rebuild only when explicitly requested instead of on every file change. File changes are still tracked while in watch mode, and all pending changes are rebuilt incrementally when a `POST` request is sent to the `/__ng_rebuild` endpoint of the development server or the `b` key is pressed in the terminal. This option has no effect when 'watch' is disabled.",
108+
"default": false
109+
},
105110
"inspect": {
106111
"default": false,
107112
"description": "Activate debugging inspector. This option only has an effect when 'SSR' or 'SSG' are enabled.",
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import { setTimeout } from 'node:timers/promises';
10+
import { executeDevServer } from '../../index';
11+
import { describeServeBuilder } from '../jasmine-helpers';
12+
import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup';
13+
14+
const REBUILD_PATH = '__ng_rebuild';
15+
16+
describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => {
17+
describe('Option: "manualRebuild"', () => {
18+
beforeEach(() => {
19+
setupTarget(harness);
20+
});
21+
22+
it('only rebuilds file changes when a rebuild is requested', async () => {
23+
harness.useTarget('serve', {
24+
...BASE_OPTIONS,
25+
watch: true,
26+
manualRebuild: true,
27+
});
28+
29+
let baseUrl = '';
30+
let rebuildResponse: Promise<Response> | undefined;
31+
32+
await harness.executeWithCases([
33+
async ({ result }) => {
34+
expect(result?.success).toBeTrue();
35+
baseUrl = result?.baseUrl as string;
36+
37+
// Nothing pending so a request should not rebuild
38+
const noChangesResponse = await fetch(new URL(REBUILD_PATH, baseUrl), {
39+
method: 'POST',
40+
});
41+
expect(noChangesResponse.status).toBe(200);
42+
expect(await noChangesResponse.json()).toEqual({ status: 'no-changes' });
43+
44+
await harness.modifyFile(
45+
'src/main.ts',
46+
(content) => content + 'console.log("abcd1234");',
47+
);
48+
49+
// Give the file watcher enough time to detect the change. No rebuild should occur.
50+
await setTimeout(1500);
51+
const before = await fetch(new URL('main.js', baseUrl));
52+
expect(await before.text()).not.toContain('abcd1234');
53+
54+
// Request a rebuild. The response is sent once the rebuild completes.
55+
rebuildResponse = fetch(new URL(REBUILD_PATH, baseUrl), { method: 'POST' });
56+
},
57+
async ({ result }) => {
58+
expect(result?.success).toBeTrue();
59+
60+
const response = await rebuildResponse;
61+
expect(response?.status).toBe(200);
62+
expect(await response?.json()).toEqual({ status: 'success' });
63+
64+
const after = await fetch(new URL('main.js', baseUrl));
65+
expect(await after.text()).toContain('abcd1234');
66+
},
67+
]);
68+
});
69+
70+
it('rejects non-POST and cross-origin rebuild requests', async () => {
71+
harness.useTarget('serve', {
72+
...BASE_OPTIONS,
73+
watch: true,
74+
manualRebuild: true,
75+
});
76+
77+
await harness.executeWithCases([
78+
async ({ result }) => {
79+
expect(result?.success).toBeTrue();
80+
const url = new URL(REBUILD_PATH, result?.baseUrl as string);
81+
82+
const getResponse = await fetch(url);
83+
expect(getResponse.status).toBe(405);
84+
85+
const crossOriginResponse = await fetch(url, {
86+
method: 'POST',
87+
headers: { origin: 'http://example.com' },
88+
});
89+
expect(crossOriginResponse.status).toBe(403);
90+
},
91+
]);
92+
});
93+
});
94+
});

‎packages/angular/build/src/builders/dev-server/vite/index.ts‎

Lines changed: 58 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,16 @@ import { join } from 'node:path';
1313
import type * as Vite from 'vite' with {
1414
'resolution-mode': 'import',
1515
};
16-
import type { ComponentStyleRecord } from '../../../tools/vite/middlewares';
16+
import {
17+
type ComponentStyleRecord,
18+
REBUILD_ROUTE,
19+
createAngularRebuildMiddleware,
20+
} from '../../../tools/vite/middlewares';
1721
import { ServerSsrMode } from '../../../tools/vite/plugins';
1822
import { updateExternalMetadata } from '../../../tools/vite/utils';
1923
import { normalizeSourceMaps } from '../../../utils';
2024
import { useComponentStyleHmr, useComponentTemplateHmr } from '../../../utils/environment-options';
25+
import { ManualRebuildController } from '../../../utils/manual-rebuild';
2126
import { Result, ResultKind } from '../../application/results';
2227
import { OutputHashing } from '../../application/schema';
2328
import {
@@ -181,6 +186,18 @@ export async function* serveWithVite(
181186
browserOptions.templateUpdates = componentsHmrCanBeUsed && useComponentTemplateHmr;
182187
browserOptions.incrementalResults = true;
183188

189+
// Setup manual rebuild support which requires watch mode to be enabled
190+
let manualRebuild: ManualRebuildController | undefined;
191+
if (serverOptions.manualRebuild) {
192+
if (browserOptions.watch) {
193+
manualRebuild = browserOptions.manualRebuild = new ManualRebuildController();
194+
} else {
195+
context.logger.warn(
196+
`The 'manualRebuild' option has no effect because the 'watch' option is disabled.`,
197+
);
198+
}
199+
}
200+
184201
// Setup the prebundling transformer that will be shared across Vite prebundling requests
185202
const prebundleTransformer = new JavaScriptTransformer(
186203
// Always enable JIT linking to support applications built with and without AOT.
@@ -434,7 +451,9 @@ export async function* serveWithVite(
434451
'ngJitMode': browserOptions.aot ? 'false' : 'true',
435452
'ngHmrMode': browserOptions.templateUpdates ? 'true' : 'false',
436453
},
437-
extensions?.middleware,
454+
manualRebuild
455+
? [createAngularRebuildMiddleware(manualRebuild), ...(extensions?.middleware ?? [])]
456+
: extensions?.middleware,
438457
transformers?.indexHtml,
439458
thirdPartySourcemaps,
440459
);
@@ -503,21 +522,45 @@ export async function* serveWithVite(
503522
// log connection information
504523
server.printUrls();
505524

525+
if (manualRebuild && serverUrl) {
526+
context.logger.info(
527+
`Manual rebuild mode enabled. Send a POST request to ${new URL(REBUILD_ROUTE, serverUrl)}` +
528+
` or press "b" to rebuild pending changes.`,
529+
);
530+
}
531+
532+
const customShortcuts: Vite.CLIShortcut<Vite.ViteDevServer>[] = [
533+
{
534+
key: 'r',
535+
description: 'force reload browser',
536+
action(server) {
537+
componentStyles.forEach((record) => record.used?.clear());
538+
server.ws.send({
539+
type: 'full-reload',
540+
path: '*',
541+
});
542+
},
543+
},
544+
];
545+
546+
if (manualRebuild) {
547+
const controller = manualRebuild;
548+
customShortcuts.push({
549+
key: 'b',
550+
description: 'rebuild pending changes',
551+
action() {
552+
void controller.requestRebuild().then(({ status }) => {
553+
if (status === 'no-changes') {
554+
context.logger.info('No pending changes to rebuild.');
555+
}
556+
});
557+
},
558+
});
559+
}
560+
506561
server.bindCLIShortcuts({
507562
print: true,
508-
customShortcuts: [
509-
{
510-
key: 'r',
511-
description: 'force reload browser',
512-
action(server) {
513-
componentStyles.forEach((record) => record.used?.clear());
514-
server.ws.send({
515-
type: 'full-reload',
516-
path: '*',
517-
});
518-
},
519-
},
520-
],
563+
customShortcuts,
521564
});
522565
}
523566

‎packages/angular/build/src/tools/vite/middlewares/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,6 @@ export {
1616
export { createAngularHeadersMiddleware } from './headers-middleware';
1717
export { createAngularComponentMiddleware } from './component-middleware';
1818
export { createChromeDevtoolsMiddleware } from './chrome-devtools-middleware';
19+
export { REBUILD_ROUTE, createAngularRebuildMiddleware } from './rebuild-middleware';
1920
export { patchHostValidationMiddleware } from './host-check-middleware';
2021
export { patchBaseMiddleware } from './base-middleware';

0 commit comments

Comments
 (0)