Skip to content

Commit 2b2263a

Browse files
authored
chore: add build state tracking to internal context (#6268)
1 parent f1a78de commit 2b2263a

File tree

6 files changed

+106
-67
lines changed

6 files changed

+106
-67
lines changed

packages/compat/webpack/src/createCompiler.ts

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import { type InitConfigsOptions, initConfigs } from './initConfigs.js';
44

55
export async function createCompiler(options: InitConfigsOptions) {
66
logger.debug('creating compiler');
7+
8+
const HOOK_NAME = 'rsbuild:compiler';
79
const { helpers, context } = options;
810
const { webpackConfigs } = await initConfigs(options);
911

@@ -20,7 +22,24 @@ export async function createCompiler(options: InitConfigsOptions) {
2022
| Rspack.Compiler
2123
| Rspack.MultiCompiler;
2224

23-
const done = (stats: Rspack.Stats) => {
25+
compiler.hooks.run.tap(HOOK_NAME, () => {
26+
context.buildState.status = 'building';
27+
});
28+
29+
compiler.hooks.watchRun.tap(HOOK_NAME, () => {
30+
context.buildState.status = 'building';
31+
});
32+
33+
compiler.hooks.invalid.tap(HOOK_NAME, () => {
34+
context.buildState.status = 'idle';
35+
context.buildState.hasErrors = false;
36+
});
37+
38+
compiler.hooks.done.tap(HOOK_NAME, (stats) => {
39+
const hasErrors = stats.hasErrors();
40+
context.buildState.hasErrors = hasErrors;
41+
context.buildState.status = 'done';
42+
2443
const statsOptions = helpers.getStatsOptions(compiler);
2544
const statsJson = stats.toJson({
2645
moduleTrace: true,
@@ -29,20 +48,13 @@ export async function createCompiler(options: InitConfigsOptions) {
2948
...statsOptions,
3049
});
3150

32-
const { message, level } = helpers.formatStats(
33-
statsJson,
34-
stats.hasErrors(),
35-
);
51+
const { message, level } = helpers.formatStats(statsJson, hasErrors);
3652

3753
if (level === 'error') {
3854
logger.error(message);
3955
} else if (level === 'warning') {
4056
logger.warn(message);
4157
}
42-
};
43-
44-
compiler.hooks.done.tap('rsbuild:done', (stats: unknown) => {
45-
done(stats as Rspack.Stats);
4658
});
4759

4860
if (context.action === 'dev') {

packages/core/src/createContext.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,5 +212,9 @@ export async function createContext(
212212
config: { ...rsbuildConfig },
213213
originalConfig: userConfig,
214214
specifiedEnvironments,
215+
buildState: {
216+
status: 'idle',
217+
hasErrors: false,
218+
},
215219
};
216220
}

packages/core/src/provider/createCompiler.ts

Lines changed: 60 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ export async function createCompiler(options: InitConfigsOptions): Promise<{
8888
rspackConfigs: Rspack.Configuration[];
8989
}> {
9090
logger.debug('creating compiler');
91+
92+
const HOOK_NAME = 'rsbuild:compiler';
9193
const { context } = options;
9294
const { rspackConfigs } = await initConfigs(options);
9395

@@ -122,7 +124,7 @@ export async function createCompiler(options: InitConfigsOptions): Promise<{
122124
const lazyModules: Set<string> = new Set();
123125

124126
// Collect lazy compiled modules from the infrastructure logs
125-
compiler.hooks.infrastructureLog.tap('rsbuild:compiling', (name, _, args) => {
127+
compiler.hooks.infrastructureLog.tap(HOOK_NAME, (name, _, args) => {
126128
const log = args[0];
127129
if (
128130
name === 'LazyCompilation' &&
@@ -144,7 +146,12 @@ export async function createCompiler(options: InitConfigsOptions): Promise<{
144146
}
145147
});
146148

147-
compiler.hooks.watchRun.tap('rsbuild:compiling', (compiler) => {
149+
compiler.hooks.run.tap(HOOK_NAME, () => {
150+
context.buildState.status = 'building';
151+
});
152+
153+
compiler.hooks.watchRun.tap(HOOK_NAME, (compiler) => {
154+
context.buildState.status = 'building';
148155
logRspackVersion();
149156

150157
if (!isCompiling) {
@@ -158,68 +165,72 @@ export async function createCompiler(options: InitConfigsOptions): Promise<{
158165
isCompiling = true;
159166
});
160167

168+
compiler.hooks.invalid.tap(HOOK_NAME, () => {
169+
context.buildState.status = 'idle';
170+
context.buildState.hasErrors = false;
171+
});
172+
161173
if (context.action === 'build') {
162174
// When there are multiple compilers, we only need to print the start log once
163175
const firstCompiler = isMultiCompiler
164176
? (compiler as Rspack.MultiCompiler).compilers[0]
165177
: compiler;
166-
firstCompiler.hooks.run.tap('rsbuild:run', () => {
178+
179+
firstCompiler.hooks.run.tap(HOOK_NAME, () => {
167180
logger.info('build started...');
168181
logRspackVersion();
169182
});
170183
}
171184

172-
const done = (stats: Rspack.Stats | Rspack.MultiStats) => {
173-
const statsOptions = getStatsOptions(compiler);
174-
const statsJson = stats.toJson({
175-
children: true,
176-
moduleTrace: true,
177-
// get the compilation time
178-
timings: true,
179-
preset: 'errors-warnings',
180-
...statsOptions,
181-
});
185+
compiler.hooks.done.tap(
186+
HOOK_NAME,
187+
(stats: Rspack.Stats | Rspack.MultiStats) => {
188+
const hasErrors = stats.hasErrors();
189+
context.buildState.hasErrors = hasErrors;
190+
context.buildState.status = 'done';
191+
192+
const statsOptions = getStatsOptions(compiler);
193+
const statsJson = stats.toJson({
194+
children: true,
195+
moduleTrace: true,
196+
// get the compilation time
197+
timings: true,
198+
preset: 'errors-warnings',
199+
...statsOptions,
200+
});
201+
202+
const printTime = (c: StatsCompilation, index: number) => {
203+
if (c.time) {
204+
const time = prettyTime(c.time / 1000);
205+
const { name } = rspackConfigs[index];
206+
207+
// When using multi compiler, print name to distinguish different compilers
208+
const suffix = name && isMultiCompiler ? color.dim(` (${name})`) : '';
209+
logger.ready(`built in ${time}${suffix}`);
210+
}
211+
};
212+
213+
if (!hasErrors) {
214+
// only print children compiler time when multi compiler
215+
if (isMultiCompiler && statsJson.children?.length) {
216+
statsJson.children.forEach((c, index) => {
217+
printTime(c, index);
218+
});
219+
} else {
220+
printTime(statsJson, 0);
221+
}
222+
}
182223

183-
const printTime = (c: StatsCompilation, index: number) => {
184-
if (c.time) {
185-
const time = prettyTime(c.time / 1000);
186-
const { name } = rspackConfigs[index];
224+
const { message, level } = formatStats(statsJson, hasErrors);
187225

188-
// When using multi compiler, print name to distinguish different compilers
189-
const suffix = name && isMultiCompiler ? color.dim(` (${name})`) : '';
190-
logger.ready(`built in ${time}${suffix}`);
226+
if (level === 'error') {
227+
logger.error(message);
191228
}
192-
};
193-
194-
const hasErrors = stats.hasErrors();
195-
196-
if (!hasErrors) {
197-
// only print children compiler time when multi compiler
198-
if (isMultiCompiler && statsJson.children?.length) {
199-
statsJson.children.forEach((c, index) => {
200-
printTime(c, index);
201-
});
202-
} else {
203-
printTime(statsJson, 0);
229+
if (level === 'warning') {
230+
logger.warn(message);
204231
}
205-
}
206-
207-
const { message, level } = formatStats(statsJson, hasErrors);
208-
209-
if (level === 'error') {
210-
logger.error(message);
211-
}
212-
if (level === 'warning') {
213-
logger.warn(message);
214-
}
215232

216-
isCompiling = false;
217-
};
218-
219-
compiler.hooks.done.tap(
220-
'rsbuild:done',
221-
(stats: Rspack.Stats | Rspack.MultiStats) => {
222-
done(stats);
233+
isCompiling = false;
223234
},
224235
);
225236

packages/core/src/types/config.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1357,14 +1357,14 @@ export type OutputStructure = 'flat' | 'nested';
13571357
/**
13581358
* custom properties
13591359
* e.g. { name: 'viewport' content: 'width=500, initial-scale=1' }
1360-
* */
1360+
*/
13611361
export type MetaAttrs = { [attrName: string]: string | boolean };
13621362

13631363
export type MetaOptions = {
13641364
/**
13651365
* name content pair
13661366
* e.g. { viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no' }`
1367-
* */
1367+
*/
13681368
[name: string]: string | false | MetaAttrs;
13691369
};
13701370

@@ -1886,7 +1886,7 @@ export type AllowedEnvironmentDevKeys =
18861886

18871887
/**
18881888
* The Rsbuild config to run in the specified environment.
1889-
* */
1889+
*/
18901890
export interface EnvironmentConfig {
18911891
/**
18921892
* Options for local development.
@@ -1934,7 +1934,7 @@ export type LogLevel = 'info' | 'warn' | 'error' | 'silent';
19341934

19351935
/**
19361936
* The Rsbuild config.
1937-
* */
1937+
*/
19381938
export interface RsbuildConfig extends EnvironmentConfig {
19391939
/**
19401940
* Specify the build mode for Rsbuild, as each mode has different default behavior and optimizations.

packages/core/src/types/context.ts

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ export type RsbuildContext = {
2828
* // ...
2929
* });
3030
* await rsbuild.startDevServer();
31-
* console.log(rsbuild.context.devServer); // { hostname: 'localhost', port: 3000, https: false }
31+
* console.log(rsbuild.context.devServer);
32+
* // { hostname: 'localhost', port: 3000, https: false }
3233
* }
3334
* ```
3435
*/
@@ -61,6 +62,15 @@ export type RsbuildContext = {
6162
callerName: string;
6263
};
6364

65+
export type BuildStatus = 'idle' | 'building' | 'done';
66+
67+
export type BuildState = {
68+
/** Current build status */
69+
status: BuildStatus;
70+
/** Whether there are build errors */
71+
hasErrors: boolean;
72+
};
73+
6474
/** The inner context. */
6575
export type InternalContext = RsbuildContext & {
6676
/** All hooks. */
@@ -73,12 +83,14 @@ export type InternalContext = RsbuildContext & {
7383
normalizedConfig?: NormalizedConfig;
7484
/**
7585
* Get the plugin API.
76-
*
77-
* When environment is undefined, the global plugin API is returned, which can be used in all environments.
78-
* */
86+
* When environment is undefined, the global plugin API is returned, which
87+
* can be used in all environments.
88+
*/
7989
getPluginAPI?: (environment?: string) => RsbuildPluginAPI;
8090
/** The environment context. */
8191
environments: Record<string, EnvironmentContext>;
8292
/** Only build specified environment. */
8393
specifiedEnvironments?: string[];
94+
/** Build state information */
95+
buildState: BuildState;
8496
};

packages/core/src/types/plugin.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ export type ModifyWebpackChainUtils = ModifyChainUtils & {
154154
CHAIN_ID: ChainIdentifier;
155155
/**
156156
* @deprecated Use target instead.
157-
* */
157+
*/
158158
name: string;
159159
/**
160160
* @deprecated Use HtmlPlugin instead.

0 commit comments

Comments
 (0)