Skip to content

Commit f4a588c

Browse files
authored
refactor: optimize environment handling with environmentList (#6560)
1 parent 097fcad commit f4a588c

File tree

14 files changed

+78
-99
lines changed

14 files changed

+78
-99
lines changed

packages/core/src/createContext.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ export async function updateEnvironmentContext(
115115
};
116116

117117
// EnvironmentContext is readonly.
118-
context.environments[name] = new Proxy(environmentContext, {
118+
const readonlyEnvironmentContext = new Proxy(environmentContext, {
119119
get(target, prop: keyof EnvironmentContext) {
120120
return target[prop];
121121
},
@@ -130,16 +130,17 @@ export async function updateEnvironmentContext(
130130
return true;
131131
},
132132
});
133+
134+
context.environmentList[index] = readonlyEnvironmentContext;
135+
context.environments[name] = readonlyEnvironmentContext;
133136
}
134137
}
135138

136139
export function updateContextByNormalizedConfig(
137140
context: InternalContext,
138141
): void {
139142
// Try to get the parent dist path from all environments
140-
const distPaths = Object.values(context.environments).map(
141-
(item) => item.distPath,
142-
);
143+
const distPaths = context.environmentList.map((item) => item.distPath);
143144
context.distPath = getCommonParentPath(distPaths);
144145
}
145146

@@ -204,6 +205,7 @@ export async function createContext(
204205
callerName: options.callerName,
205206
bundlerType,
206207
environments: {},
208+
environmentList: [],
207209
publicPathnames: [],
208210
hooks: initHooks(),
209211
config: { ...rsbuildConfig },

packages/core/src/hooks.ts

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { isMultiCompiler } from './helpers/compiler';
33
import type {
44
AsyncHook,
55
EnvironmentAsyncHook,
6-
EnvironmentContext,
76
HookDescriptor,
87
InternalContext,
98
ModifyBundlerChainFn,
@@ -377,12 +376,7 @@ export const registerBuildHook = ({
377376
}): void => {
378377
let isFirstCompile = true;
379378

380-
const environmentList = Object.values(context.environments).reduce<
381-
EnvironmentContext[]
382-
>((prev, curr) => {
383-
prev[curr.index] = curr;
384-
return prev;
385-
}, []);
379+
const { environmentList } = context;
386380

387381
const beforeCompile = async () =>
388382
context.hooks.onBeforeBuild.callBatch({
@@ -459,12 +453,7 @@ export const registerDevHook = ({
459453
}): void => {
460454
let isFirstCompile = true;
461455

462-
const environmentList = Object.values(context.environments).reduce<
463-
EnvironmentContext[]
464-
>((prev, curr) => {
465-
prev[curr.index] = curr;
466-
return prev;
467-
}, []);
456+
const { environmentList } = context;
468457

469458
const beforeCompile = async () =>
470459
context.hooks.onBeforeDevCompile.callBatch({

packages/core/src/plugins/nonce.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,9 @@ export const pluginNonce = (): RsbuildPlugin => ({
88
setup(api) {
99
api.onAfterCreateCompiler(({ compiler, environments }) => {
1010
const environmentList = Object.values(environments);
11-
const nonces = environmentList.map((environment) => {
12-
const { nonce } = environment.config.security;
13-
14-
return nonce;
15-
});
11+
const nonces = Object.values(environments).map(
12+
(environment) => environment.config.security.nonce,
13+
);
1614

1715
if (!nonces.some((nonce) => !!nonce)) {
1816
return;

packages/core/src/provider/createCompiler.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,8 @@ export async function createCompiler(options: InitConfigsOptions): Promise<{
207207
if (!hasErrors) {
208208
// only print children compiler time when multi compiler
209209
if (isMultiCompiler && stats.children?.length) {
210-
stats.children.forEach((c, index) => {
211-
printTime(c, index);
210+
stats.children.forEach((item, index) => {
211+
printTime(item, index);
212212
});
213213
} else {
214214
printTime(stats, 0);

packages/core/src/server/assets-middleware/getFileFromUrl.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,8 @@ export async function getFileFromUrl(
5151
});
5252
};
5353

54-
const { environments, publicPathnames } = context;
55-
const distPaths = Object.values(environments).map((env) => env.distPath);
54+
const { environmentList, publicPathnames } = context;
55+
const distPaths = environmentList.map((env) => env.distPath);
5656
const possibleFilenames = new Set<string>();
5757

5858
// First, add paths that match the public prefix for more accurate resolution

packages/core/src/server/assets-middleware/index.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -211,12 +211,10 @@ export const assetsMiddleware = async ({
211211
resolvedPort: number;
212212
}): Promise<AssetsMiddleware> => {
213213
const resolvedHost = await resolveHostname(config.server.host);
214-
const { environments } = context;
214+
const { environments, environmentList } = context;
215215

216216
const setupCompiler = (compiler: Compiler, index: number) => {
217-
const environment = Object.values(environments).find(
218-
(env) => env.index === index,
219-
);
217+
const environment = environmentList[index];
220218
if (!environment) {
221219
return;
222220
}
@@ -261,7 +259,11 @@ export const assetsMiddleware = async ({
261259
});
262260
});
263261

264-
const writeToDisk = resolveWriteToDiskConfig(config.dev, environments);
262+
const writeToDisk = resolveWriteToDiskConfig(
263+
config.dev,
264+
environments,
265+
environmentList,
266+
);
265267
if (writeToDisk) {
266268
setupWriteToDisk(compilers, writeToDisk);
267269
}

packages/core/src/server/assets-middleware/setupWriteToDisk.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@ export type ResolvedWriteToDisk =
2222
export const resolveWriteToDiskConfig = (
2323
config: NormalizedDevConfig,
2424
environments: Record<string, EnvironmentContext>,
25+
environmentList: EnvironmentContext[],
2526
): ResolvedWriteToDisk => {
26-
const writeToDiskValues = Object.values(environments).map(
27+
const writeToDiskValues = environmentList.map(
2728
(env) => env.config.dev.writeToDisk,
2829
);
2930
if (new Set(writeToDiskValues).size === 1) {

packages/core/src/server/devServer.ts

Lines changed: 39 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -303,63 +303,45 @@ export async function createDevServer<
303303
(_stats, entryName, utils) => getTransformedHtml(entryName, utils),
304304
);
305305

306-
const environmentAPI = Object.fromEntries(
307-
Object.entries(context.environments).map(([name, environment]) => {
308-
return [
309-
name,
310-
{
311-
getStats: async () => {
312-
if (!buildManager) {
313-
throw new Error(
314-
`${color.dim('[rsbuild:server]')} Can not call ` +
315-
`${color.yellow('getStats')} when ` +
316-
`${color.yellow('runCompile')} is false`,
317-
);
318-
}
319-
await waitLastCompileDone;
320-
return lastStats[environment.index];
321-
},
322-
context: environment,
323-
loadBundle: async <T>(entryName: string) => {
324-
if (!buildManager) {
325-
throw new Error(
326-
`${color.dim('[rsbuild:server]')} Can not call ` +
327-
`${color.yellow('loadBundle')} when ` +
328-
`${color.yellow('runCompile')} is false`,
329-
);
330-
}
331-
await waitLastCompileDone;
332-
return cacheableLoadBundle(
333-
lastStats[environment.index],
334-
entryName,
335-
{
336-
readFileSync: buildManager.readFileSync,
337-
environment,
338-
},
339-
) as T;
340-
},
341-
getTransformedHtml: async (entryName: string) => {
342-
if (!buildManager) {
343-
throw new Error(
344-
`${color.dim('[rsbuild:server]')} Can not call ` +
345-
`${color.yellow('getTransformedHtml')} when ` +
346-
`${color.yellow('runCompile')} is false`,
347-
);
348-
}
349-
await waitLastCompileDone;
350-
return cacheableTransformedHtml(
351-
lastStats[environment.index],
352-
entryName,
353-
{
354-
readFileSync: buildManager.readFileSync,
355-
environment,
356-
},
357-
);
358-
},
359-
},
360-
];
361-
}),
362-
);
306+
const environmentAPI: EnvironmentAPI = {};
307+
308+
const getErrorMsg = (method: string) =>
309+
`${color.dim('[rsbuild:server]')} Can not call ` +
310+
`${color.yellow(method)} when ` +
311+
`${color.yellow('runCompile')} is false`;
312+
313+
context.environmentList.forEach((environment, index) => {
314+
environmentAPI[environment.name] = {
315+
context: environment,
316+
getStats: async () => {
317+
if (!buildManager) {
318+
throw new Error(getErrorMsg('getStats'));
319+
}
320+
await waitLastCompileDone;
321+
return lastStats[index];
322+
},
323+
loadBundle: async <T>(entryName: string) => {
324+
if (!buildManager) {
325+
throw new Error(getErrorMsg('loadBundle'));
326+
}
327+
await waitLastCompileDone;
328+
return cacheableLoadBundle(lastStats[index], entryName, {
329+
readFileSync: buildManager.readFileSync,
330+
environment,
331+
}) as T;
332+
},
333+
getTransformedHtml: async (entryName: string) => {
334+
if (!buildManager) {
335+
throw new Error(getErrorMsg('getTransformedHtml'));
336+
}
337+
await waitLastCompileDone;
338+
return cacheableTransformedHtml(lastStats[index], entryName, {
339+
readFileSync: buildManager.readFileSync,
340+
environment,
341+
});
342+
},
343+
};
344+
});
363345

364346
const connect = requireCompiledPackage('connect');
365347
const middlewares = connect();

packages/core/src/server/helper.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ export const stripBase = (path: string, base: string): string => {
8888
};
8989

9090
export const getRoutes = (context: InternalContext): Routes => {
91-
const environmentWithHtml = Object.values(context.environments).filter(
91+
const environmentWithHtml = context.environmentList.filter(
9292
(item) => Object.keys(item.htmlPaths).length > 0,
9393
);
9494
if (environmentWithHtml.length === 0) {

packages/core/src/server/prodServer.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ export async function startProdServer(
190190
pwd: context.rootPath,
191191
output: {
192192
path: context.distPath,
193-
assetPrefixes: Object.values(context.environments).map((e) =>
193+
assetPrefixes: context.environmentList.map((e) =>
194194
getPathnameFromUrl(e.config.output.assetPrefix),
195195
),
196196
},

0 commit comments

Comments
 (0)