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.

🐛 fix: 修复开发环境 StyleX 初始化与预编译卡顿 (#21520)

Mocha312ed3e5467e
diff --git a/plugins/vite/lobeUiImports.ts b/plugins/vite/lobeUiImports.ts
index 631cbd8155b..4f20ecfd7bc 100644
--- a/plugins/vite/lobeUiImports.ts
+++ b/plugins/vite/lobeUiImports.ts
@@ -9,6 +9,9 @@ const NAMED_EXPORT_PREFIX = 'virtual:lobe-ui-named:';
const RESOLVED_NAMED_EXPORT_PREFIX = `\0${NAMED_EXPORT_PREFIX}`;
const BARRELS = ['', 'awesome', 'brand', 'chat', 'color', 'icons', 'mdx'] as const;
+export const lobeUiImportSources = BARRELS.map((barrel) =>
+ barrel ? `@lobehub/ui/${barrel}` : '@lobehub/ui',
+);
interface MemberSource {
imported: string;
diff --git a/plugins/vite/stylex.tokens.test.ts b/plugins/vite/stylex.tokens.test.ts
index b5c173af18b..5702a1ca77b 100644
--- a/plugins/vite/stylex.tokens.test.ts
+++ b/plugins/vite/stylex.tokens.test.ts
@@ -172,3 +172,32 @@ export const overlay = stylex.defineConsts({ ring: '3px solid rgb(1, 2, 3)' });
expect(stylexAliases([path.join(root, 'src')])['@/*']).toEqual([path.join(root, 'src/*')]);
});
});
+
+describe('StyleX dev CSS collection', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ });
+ it('resolves token constants before the browser loads their modules', async () => {
+ vi.stubEnv('VITEST', 'false');
+ vi.stubEnv('NODE_ENV', 'development');
+ vi.resetModules();
+ const { stylexPlugin } = await import('./stylex');
+ const plugins = (stylexPlugin() as unknown[]).flat(Infinity) as Array<{
+ __stylexCollectCss?: () => string;
+ buildStart?: () => Promise<void> | void;
+ transform?: (code: string, id: string) => Promise<unknown>;
+ }>;
+ const compiler = plugins.find((plugin) => plugin.__stylexCollectCss);
+ if (!compiler?.buildStart || !compiler.transform || !compiler.__stylexCollectCss)
+ throw new Error('StyleX compiler hooks are missing');
+
+ await compiler.buildStart();
+ await compiler.transform(consumerSource, path.join(root, 'src/stylex-token-consumer.js'));
+
+ const css = compiler.__stylexCollectCss();
+ expect(css).toContain('color: var(--lobe-color-text)');
+ expect(css).toMatch(/@media[^{]+575\.98px/);
+ expect(css).not.toMatch(/var\(--(?!lobe-)[^)]+\)/);
+ });
+});
diff --git a/plugins/vite/stylex.ts b/plugins/vite/stylex.ts
index b241c6b3d44..15d3760e920 100644
--- a/plugins/vite/stylex.ts
+++ b/plugins/vite/stylex.ts
@@ -1,9 +1,10 @@
-import { existsSync } from 'node:fs';
+import { existsSync, readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import stylex from '@stylexjs/unplugin/vite';
-import type { PluginOption, UserConfig } from 'vite';
+import type { Plugin, PluginOption, UserConfig } from 'vite';
import { stylexProxiedDevCssPlugin } from './stylexDevCss';
import { createStylexEntryCss } from './stylexEntryCss';
@@ -72,10 +73,7 @@ export function stylexPlugin({ overlaySrcDirs }: StylexPluginOptions = {}): Plug
},
});
- const plugins = (Array.isArray(plugin) ? plugin : [plugin]) as Array<{
- config?: unknown;
- configureServer?: unknown;
- }>;
+ const plugins = (Array.isArray(plugin) ? plugin : [plugin]) as Plugin[];
for (const item of plugins) {
// @lobehub/ui depends on @stylexjs/stylex but ships precompiled CSS. This hook
// would pull that package out of dependency pre-bundling.
@@ -83,6 +81,20 @@ export function stylexPlugin({ overlaySrcDirs }: StylexPluginOptions = {}): Plug
// The unplugin polls a shared CSS store from configureServer and keeps Vitest's
// Vite server alive after the run.
if (isTest) delete item.configureServer;
+ if (!isTest && typeof item.buildStart === 'function' && typeof item.transform === 'function') {
+ const buildStart = item.buildStart;
+ const transform = item.transform;
+ const require = createRequire(path.join(repoRoot, 'package.json'));
+ item.buildStart = async function (options) {
+ await buildStart.call(this, options);
+ // commonJS token references are placeholders until their defineConsts
+ // modules are collected. Register them before dev CSS can be requested.
+ for (const tokenModule of stylexTokenModules) {
+ const filename = require.resolve(tokenModule);
+ await Reflect.apply(transform, this, [readFileSync(filename, 'utf8'), filename]);
+ }
+ };
+ }
}
const [locateEntryCss, verifyEntryCss] = entryCss.plugins;
diff --git a/vite.config.ts b/vite.config.ts
index 054be6b7437..135b45086c8 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -10,6 +10,7 @@ import { VitePWA } from 'vite-plugin-pwa';
import { canvasRuntimeEntries } from './plugins/vite/canvasRuntime';
import { customBrandingLoadingScreen } from './plugins/vite/customBrandingLoadingScreen';
import { viteEnvRestartKeys } from './plugins/vite/envRestartKeys';
+import { lobeUiImportSources } from './plugins/vite/lobeUiImports';
import {
createSharedRolldownOutput,
sharedModulePreload,
@@ -143,7 +144,28 @@ export default defineConfig({
dedupe: sharedRendererDedupe,
tsconfigPaths: true,
},
- optimizeDeps: sharedOptimizeDeps,
+ optimizeDeps: {
+ ...sharedOptimizeDeps,
+ // Web rewrites UI imports to individual modules. Forcing its root barrel
+ // into the optimizer would still pre-bundle every deferred UI dependency.
+ include: [
+ ...sharedOptimizeDeps.include.filter((dependency) => dependency !== '@lobehub/ui'),
+ // Excluded ESM UI modules still need their nested CommonJS shims optimized.
+ '@lobehub/ui > use-sync-external-store/shim',
+ '@lobehub/ui > use-sync-external-store/shim/with-selector',
+ '@lobehub/ui > lru_map',
+ '@lobehub/ui > style-to-js',
+ '@lobehub/ui > @primer/octicons',
+ '@lobehub/ui > extend',
+ '@lobehub/ui > dayjs/plugin/advancedFormat.js',
+ '@lobehub/ui > dayjs/plugin/customParseFormat.js',
+ '@lobehub/ui > dayjs/plugin/localeData.js',
+ '@lobehub/ui > dayjs/plugin/weekday.js',
+ '@lobehub/ui > dayjs/plugin/weekOfYear.js',
+ '@lobehub/ui > dayjs/plugin/weekYear.js',
+ ],
+ exclude: [...sharedOptimizeDeps.exclude, ...lobeUiImportSources, '@lobehub/icons'],
+ },
plugins: [
isMobile &&
isDev && {
@@ -350,6 +372,9 @@ export default defineConfig({
// port and injects it via env; never silently drift to another port, since
// downstream consumers locate this server through that env contract.
strictPort: true,
+ // Transform imports when requested, rather than racing ahead through the
+ // chat shell's large dependency graph while the optimizer is still running.
+ preTransformRequests: false,
proxy: {
'/api': `http://localhost:${process.env.PORT || 3010}`,
'/oidc': `http://localhost:${process.env.PORT || 3010}`,
@@ -357,52 +382,11 @@ export default defineConfig({
'/webapi': `http://localhost:${process.env.PORT || 3010}`,
},
warmup: {
+ // Pre-transform entry modules; Vite follows their static imports on demand.
+ // Whole-tree globs also compile lazy routes, tests and server-only packages.
clientFiles: [
- // src/ business code
- './src/initialize.ts',
- './src/spa/**/*.tsx',
- './src/business/**/*.{ts,tsx}',
- './src/components/**/*.{ts,tsx}',
- './src/const/**/*.ts',
- './src/features/**/*.{ts,tsx}',
- './src/helpers/**/*.ts',
- './src/hooks/**/*.{ts,tsx}',
- './src/layout/**/*.{ts,tsx}',
- './src/libs/**/*.{ts,tsx}',
- './src/routes/**/*.{ts,tsx}',
- './src/services/**/*.ts',
- './src/store/**/*.{ts,tsx}',
- './src/styles/**/*.ts',
- './src/utils/**/*.{ts,tsx}',
-
- // monorepo packages
- './packages/types/src/**/*.ts',
- './packages/const/src/**/*.ts',
- './packages/utils/src/**/*.ts',
- './packages/context-engine/src/**/*.ts',
- './packages/prompts/src/**/*.ts',
- './packages/model-bank/src/**/*.ts',
- './packages/model-runtime/src/**/*.ts',
- './packages/agent-runtime/src/**/*.ts',
- './packages/conversation-flow/src/**/*.ts',
- './packages/electron-client-ipc/src/**/*.ts',
- './packages/builtin-agents/src/**/*.ts',
- './packages/builtin-skills/src/**/*.ts',
- './packages/builtin-tool-*/src/**/*.ts',
- './packages/builtin-tools/src/**/*.ts',
- './packages/business/*/src/**/*.ts',
- './packages/business-server/src/**/*.ts',
- './packages/config/src/**/*.ts',
- './packages/edge-config/src/**/*.ts',
- './packages/editor-runtime/src/**/*.ts',
- './packages/env/src/**/*.ts',
- './packages/trpc/src/**/*.{ts,tsx}',
- './packages/app-config/src/**/*.ts',
- './packages/locales/src/**/*.ts',
- './packages/fetch-sse/src/**/*.ts',
- './packages/desktop-bridge/src/**/*.ts',
- './packages/python-interpreter/src/**/*.ts',
- './packages/agent-manager-runtime/src/**/*.ts',
+ './src/spa/entry.auth.tsx',
+ ...(isAuth ? [] : [isMobile ? './src/spa/entry.mobile.tsx' : './src/spa/entry.web.tsx']),
],
},
watch: createViteWatchOptions([__dirname]),