Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚡️ perf(desktop): split first-screen chunks per renderer entry and drop the provider page require (#20324)

Innei487c8eb310fa
diff --git a/apps/desktop/vite.renderer.config.ts b/apps/desktop/vite.renderer.config.ts
index 46fcc2b6c51..ca0c5c6a7cd 100644
--- a/apps/desktop/vite.renderer.config.ts
+++ b/apps/desktop/vite.renderer.config.ts
@@ -30,6 +30,11 @@ import {
} from './vite.shared';
const RENDERER_OUT_DIR = path.resolve(__dirname, 'dist/renderer');
+const RENDERER_INPUTS = {
+ main: path.resolve(__dirname, 'index.html'),
+ overlay: path.resolve(__dirname, 'overlay.html'),
+ popup: path.resolve(__dirname, 'popup.html'),
+};
/**
* The repository public directory can contain ignored web build outputs after
@@ -230,12 +235,12 @@ export default defineConfig(async (env) => {
outDir: RENDERER_OUT_DIR,
reportCompressedSize: false,
rolldownOptions: {
- input: {
- main: path.resolve(__dirname, 'index.html'),
- overlay: path.resolve(__dirname, 'overlay.html'),
- popup: path.resolve(__dirname, 'popup.html'),
- },
- output: createSharedRolldownOutput({ splitInitial: false, strictExecutionOrder: true }),
+ input: RENDERER_INPUTS,
+ output: createSharedRolldownOutput({
+ initialEntries: RENDERER_INPUTS,
+ strictExecutionOrder: true,
+ }),
+ preserveEntrySignatures: 'allow-extension',
},
sourcemap: false,
target: RENDERER_CHROME_TARGET,
diff --git a/plugins/vite/sharedRendererConfig.test.ts b/plugins/vite/sharedRendererConfig.test.ts
index 868e6f2aff1..2551afb25e8 100644
--- a/plugins/vite/sharedRendererConfig.test.ts
+++ b/plugins/vite/sharedRendererConfig.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest';
import {
__testing,
+ createEntrySetLabeler,
+ createSharedRolldownOutput,
sharedModulePreload,
sharedOptimizeDeps,
sharedRendererDedupe,
@@ -283,3 +285,100 @@ describe('sharedChunkFileNames', () => {
).toBe('assets/[name]-[hash].js');
});
});
+
+const fakeGraph: Record<string, string[]> = {
+ '/main.tsx': ['/shared.ts', '/main-only.ts', '/node_modules/antd/es/button.js'],
+ '/overlay.tsx': ['/shared.ts', '/overlay-only.ts'],
+ '/popup.tsx': ['/shared.ts', '/main-only.ts'],
+ '/shared.ts': ['/leaf.ts'],
+ '/main-only.ts': [],
+ '/overlay-only.ts': [],
+ '/leaf.ts': [],
+ '/lazy.ts': [],
+ '/node_modules/antd/es/button.js': [],
+};
+const fakeCtx = {
+ getModuleInfo: (id: string) => (id in fakeGraph ? { importedIds: fakeGraph[id] } : null),
+};
+const fakeEntries = { main: '/main.tsx', overlay: '/overlay.tsx', popup: '/popup.tsx' };
+
+describe('createEntrySetLabeler', () => {
+ const label = createEntrySetLabeler(fakeEntries);
+
+ it('labels each first-screen module by the entries that statically reach it', () => {
+ expect(label('/leaf.ts', fakeCtx)).toBe('main+overlay+popup');
+ expect(label('/main-only.ts', fakeCtx)).toBe('main+popup');
+ expect(label('/overlay-only.ts', fakeCtx)).toBe('overlay');
+ expect(label('/main.tsx', fakeCtx)).toBe('main');
+ });
+
+ it('leaves modules no entry reaches statically unlabeled', () => {
+ expect(label('/lazy.ts', fakeCtx)).toBeNull();
+ });
+
+ it('matches Windows entry paths against normalized module graph IDs', () => {
+ const windowsLabel = createEntrySetLabeler({
+ main: 'C:\\repo\\main.tsx',
+ overlay: 'C:\\repo\\overlay.tsx',
+ popup: 'C:\\repo\\popup.tsx',
+ });
+ const graph = Object.fromEntries(
+ Object.entries(fakeGraph).map(([id, imports]) => [
+ `C:/repo${id}`,
+ { importedIds: imports.map((dependency) => `C:/repo${dependency}`) },
+ ]),
+ );
+ const ctx = { getModuleInfo: (id: string) => graph[id] ?? null };
+
+ expect(windowsLabel('C:/repo/main.tsx', ctx)).toBe('main');
+ expect(windowsLabel('C:/repo/leaf.ts', ctx)).toBe('main+overlay+popup');
+ expect(windowsLabel('C:/repo/main-only.ts', ctx)).toBe('main+popup');
+ expect(windowsLabel('C:/repo/overlay-only.ts', ctx)).toBe('overlay');
+ expect(windowsLabel('C:/repo/lazy.ts', ctx)).toBeNull();
+ });
+
+ it('fails loudly when an entry module is not in the graph', () => {
+ const broken = createEntrySetLabeler({ main: '/missing.tsx' });
+ expect(() => broken('/leaf.ts', fakeCtx)).toThrow(/missing\.tsx/);
+ });
+});
+
+type OutputGroup = ReturnType<typeof createSharedRolldownOutput>['codeSplitting']['groups'][number];
+const nameOf = (group: OutputGroup | undefined, id: string) =>
+ typeof group?.name === 'function' ? group.name(id, fakeCtx) : group?.name;
+
+describe('createSharedRolldownOutput', () => {
+ const groups = (options?: Parameters<typeof createSharedRolldownOutput>[0]) =>
+ createSharedRolldownOutput(options).codeSplitting.groups as OutputGroup[];
+ const initialGroup = (list: OutputGroup[], vendor: string) =>
+ list.find(
+ (g) =>
+ g.priority >= 10 &&
+ (g.name === vendor || nameOf(g, '/node_modules/antd/es/button.js')?.startsWith(vendor)),
+ );
+
+ it('keeps the single-name first-screen catch-all for single-entry builds', () => {
+ expect(groups().at(-1)).toMatchObject({ name: 'app-initial', tags: ['$initial'] });
+ expect(initialGroup(groups(), 'vendor-antd')).toMatchObject({ tags: ['$initial'] });
+ expect(initialGroup(groups(), 'vendor-antd')?.name).toBe('vendor-antd');
+ });
+
+ it('splits first-screen chunks, vendor groups included, per entry set for multi-entry builds', () => {
+ const output = createSharedRolldownOutput({ initialEntries: fakeEntries, splitInitial: false });
+ const list = output.codeSplitting.groups as OutputGroup[];
+
+ expect(output.codeSplitting).toMatchObject({ includeDependenciesRecursively: false });
+ expect(list.some((g) => 'tags' in g)).toBe(false);
+ expect(nameOf(list.at(-1), '/main-only.ts')).toBe('initial-main+popup');
+ expect(nameOf(list.at(-1), '/lazy.ts')).toBeNull();
+ expect(nameOf(initialGroup(list, 'vendor-antd'), '/node_modules/antd/es/button.js')).toBe(
+ 'vendor-antd-main',
+ );
+ });
+
+ it('keeps entry-set chunking for multi-entry builds without initial entries', () => {
+ const output = createSharedRolldownOutput({ splitInitial: false });
+ expect(output.codeSplitting).not.toHaveProperty('includeDependenciesRecursively');
+ expect((output.codeSplitting.groups as OutputGroup[]).some((g) => 'tags' in g)).toBe(false);
+ });
+});
diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.ts
index c7cc84496d6..c1280a3b716 100644
--- a/plugins/vite/sharedRendererConfig.ts
+++ b/plugins/vite/sharedRendererConfig.ts
@@ -318,13 +318,54 @@ export const sharedRollupOutput = {
};
interface SharedRolldownOutputOptions {
- // The $initial split assumes one HTML entry: a constant-name catch-all would
- // merge every entry's static graph, so multi-entry builds (the desktop
- // renderer's main/overlay/popup) keep rolldown's entry-set chunking.
+ // Multi-entry builds (the desktop renderer's main/overlay/popup) pass their
+ // entry modules so the first-screen catch-all is split per entry set instead
+ // of merging every entry's static graph into one chunk.
+ initialEntries?: Record<string, string>;
+ // Without initialEntries, multi-entry builds must opt out: a constant-name
+ // catch-all would merge every entry's static graph.
splitInitial?: boolean;
strictExecutionOrder?: boolean;
}
+interface ModuleGraph {
+ getModuleInfo: (id: string) => { importedIds: readonly string[] } | null;
+}
+
+// Rolldown's entry-set chunking can park a small module a first-screen chunk
+// needs inside a heavy lazy chunk, which the entry then preloads whole
+// (rolldown/rolldown#10787). Naming every first-screen chunk, vendor groups
+// included, by the set of entries that statically reach its modules rules that
+// out, and an entry still loads only the chunks whose set contains it.
+export const createEntrySetLabeler = (entries: Record<string, string>) => {
+ let reach: [label: string, ids: Set<string>][] | undefined;
+
+ const collect = (ctx: ModuleGraph, entry: string) => {
+ if (!ctx.getModuleInfo(entry))
+ throw new Error(`initial entry ${entry} is not in the module graph`);
+ const ids = new Set<string>();
+ const stack = [entry];
+ while (stack.length > 0) {
+ const id = stack.pop()!;
+ if (ids.has(id)) continue;
+ const info = ctx.getModuleInfo(id);
+ if (!info) continue;
+ ids.add(id);
+ stack.push(...info.importedIds);
+ }
+ return ids;
+ };
+
+ return (id: string, ctx: ModuleGraph) => {
+ reach ??= Object.entries(entries).map(([label, entry]) => [
+ label,
+ collect(ctx, entry.replaceAll('\\', '/')),
+ ]);
+ const labels = reach.filter(([, ids]) => ids.has(id)).map(([label]) => label);
+ return labels.length > 0 ? labels.join('+') : null;
+ };
+};
+
// @lobehub/ui members on the first-screen path of dist/desktop, measured with
// bundle-size-gate --type entry-graph. lobeUiImports splits the barrel into one
// module per member; folding the eager ones back into one chunk keeps the heavy
@@ -339,7 +380,7 @@ const isUiCoreModule = (id: string) => {
};
interface Group {
- name: string | ((id: string) => string | null);
+ name: string | ((id: string, ctx: ModuleGraph) => string | null);
priority: number;
test?: RegExp | ((id: string) => boolean);
}
@@ -353,17 +394,44 @@ const isNamedLazyChunk = (name: string) => name.startsWith('i18n-') || name.star
// Every module left over in the entry's static graph is needed for the first
// paint anyway, so folding them into one chunk costs nothing on first load and
// stops the entry-set splitter from fanning them out into dozens of small files.
-const splitByInitial = (groups: Group[]) => [
- ...groups.map((g) => ({ ...g, priority: g.priority + 10, tags: ['$initial' as const] })),
- {
- name: (id: string) => {
- const name = sharedManualChunks(id);
- return name && isNamedLazyChunk(name) ? name : null;
+const splitByInitial = (
+ groups: Group[],
+ label?: (id: string, ctx: ModuleGraph) => string | null,
+) => {
+ // Rolldown's $initial tag skips re-export targets the first screen never
+ // uses, yet with strictExecutionOrder their barrel's init still calls them,
+ // so the chunks holding them get preloaded anyway. The labeler's static walk
+ // covers those modules, so entry-set mode selects by label instead of tag.
+ const initial = label ? {} : { tags: ['$initial' as const] };
+ const withEntrySet =
+ (base: Group['name']): Group['name'] =>
+ (id, ctx) => {
+ const name = typeof base === 'string' ? base : base(id, ctx);
+ const set = name && label!(id, ctx);
+ return set ? `${name}-${set}` : null;
+ };
+
+ return [
+ ...groups.map((g) => ({
+ ...g,
+ name: label ? withEntrySet(g.name) : g.name,
+ priority: g.priority + 10,
+ ...initial,
+ })),
+ {
+ name: (id: string) => {
+ const name = sharedManualChunks(id);
+ return name && isNamedLazyChunk(name) ? name : null;
+ },
+ priority: 3,
},
- priority: 3,
- },
- { name: 'app-initial', priority: 0, tags: ['$initial' as const] },
-];
+ {
+ name: label ? withEntrySet('initial') : 'app-initial',
+ priority: 0,
+ ...initial,
+ },
+ ];
+};
// Recursive dependency capture ignores the $initial tag: a lazy group would
// drag first-screen modules into its chunk and the entry would then preload it.
@@ -382,13 +450,15 @@ export const createSharedRolldownOutput = (options: SharedRolldownOutputOptions
},
{ name: 'vendor-ui-core', priority: 1, test: isUiCoreModule },
];
- const splitInitial = options.splitInitial ?? true;
+ const { initialEntries } = options;
+ const splitInitial = Boolean(initialEntries) || (options.splitInitial ?? true);
+ const label = initialEntries && createEntrySetLabeler(initialEntries);
return {
chunkFileNames: sharedChunkFileNames,
strictExecutionOrder: options.strictExecutionOrder ?? true,
codeSplitting: splitInitial
- ? { groups: splitByInitial(groups), includeDependenciesRecursively: false }
+ ? { groups: splitByInitial(groups, label), includeDependenciesRecursively: false }
: { groups },
};
};
diff --git a/src/features/Settings/provider/index.tsx b/src/features/Settings/provider/index.tsx
index 005f37ec936..dd4e397898e 100644
--- a/src/features/Settings/provider/index.tsx
+++ b/src/features/Settings/provider/index.tsx
@@ -55,18 +55,4 @@ export const ProviderDetailPage = memo(() => {
ProviderDetailPage.displayName = 'ProviderDetailPage';
-// Default export for backward compatibility (used by SettingsContent)
-type ProviderPageType = {
- mobile?: boolean;
-};
-
-const ProviderPage = (props: ProviderPageType) => {
- const { mobile } = props;
-
- // For mobile or when used via SettingsContent, use the old Page component
- // This is a fallback for non-router usage
- const OldPage = require('./(list)').default;
- return <OldPage mobile={mobile} />;
-};
-
-export default ProviderPage;
+export { default } from './(list)';