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(vite): precompile pure createStaticStyles at build time (#19066)

Innei94d06945e1fb
diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.ts
index 3e6649ff38b..5728d81e6c8 100644
--- a/plugins/vite/sharedRendererConfig.ts
+++ b/plugins/vite/sharedRendererConfig.ts
@@ -8,6 +8,7 @@ import { lobeUiImports } from './lobeUiImports';
import { viteMarkdownImport } from './markdownImport';
import { viteNodeModuleStub } from './nodeModuleStub';
import { vitePlatformResolve } from './platformResolve';
+import { viteStaticStylesPrecompile } from './staticStylesPrecompile';
/**
* Shared manual chunk naming — groups leaf-node modules to reduce chunk file count.
@@ -384,6 +385,7 @@ export function sharedRendererPlugins(options: SharedRendererOptions) {
hotKeys: ['altKey', 'ctrlKey'],
}),
react(),
+ viteStaticStylesPrecompile(),
...(options.platform === 'desktop' ? [] : [...lobeIconImports(), ...lobeUiImports()]),
];
}
diff --git a/plugins/vite/staticStylesPrecompile.test.ts b/plugins/vite/staticStylesPrecompile.test.ts
new file mode 100644
index 00000000000..3fac36a2f8c
--- /dev/null
+++ b/plugins/vite/staticStylesPrecompile.test.ts
@@ -0,0 +1,227 @@
+// @vitest-environment node
+import { build, parseAst, type Plugin } from 'vite';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
+
+import {
+ loadAntdStyleEvaluator,
+ precompileStaticStyles,
+ splitRules,
+ viteStaticStylesPrecompile,
+} from './staticStylesPrecompile';
+import { insertPrecompiledStyle } from './staticStylesRuntime';
+
+let evaluator: Awaited<ReturnType<typeof loadAntdStyleEvaluator>>;
+
+beforeAll(async () => {
+ evaluator = await loadAntdStyleEvaluator();
+});
+
+const CALLBACK = `({ css, responsive }) => ({
+ root: css\`
+ display: flex;
+ color: \${cssVar.colorTextSecondary};
+ &:hover { color: \${cssVar.colorText}; }
+ \${responsive.mobile} { padding: 0; }
+ \`,
+ 'text-2': css\`font-size: 12px;\`,
+})`;
+
+const PURE = `
+import { createStaticStyles, cssVar } from 'antd-style';
+export const styles = createStaticStyles(${CALLBACK});
+`;
+
+describe('splitRules', () => {
+ it('splits top-level rules and keeps nested blocks together', () => {
+ const css = `.a{color:red;}.a:hover{color:blue;}@media (max-width: 479.98px){.a{padding:0;}}.b{content:"}";}`;
+ expect(splitRules(css)).toEqual([
+ '.a{color:red;}',
+ '.a:hover{color:blue;}',
+ '@media (max-width: 479.98px){.a{padding:0;}}',
+ '.b{content:"}";}',
+ ]);
+ });
+});
+
+describe('precompileStaticStyles', () => {
+ it('replaces a pure callback with precompiled rules', () => {
+ const output = precompileStaticStyles(PURE, evaluator)!;
+ expect(output).not.toContain('createStaticStyles(');
+ expect(output).toContain(
+ "import { insertPrecompiledStyle as __lobeStaticStyle } from 'virtual:lobe-static-styles-runtime';",
+ );
+ expect(output).toMatch(
+ /"root": __lobeStaticStyle\("acss-[a-z0-9]+", \[".acss-[a-z0-9]+\{display:/,
+ );
+ expect(output).toContain('color:var(--ant-color-text-secondary)');
+ expect(output).toContain('@media (max-width: 479.98px){.acss-');
+ expect(output).toContain('"text-2": __lobeStaticStyle(');
+ expect(output).toMatch(
+ /__lobeStaticStyle\("acss-[a-z0-9]+", \["\.acss-[a-z0-9]+\{font-size:12px;\}"\]\)/,
+ );
+ expect(output).not.toContain('font-size: 12px;');
+ });
+
+ it('matches the class names antd-style produces at runtime', () => {
+ const output = precompileStaticStyles(PURE, evaluator)!;
+
+ const callback = new Function('cssVar', `return ${CALLBACK};`)(evaluator.cssVar);
+ const runtime = evaluator.createStaticStyles(callback);
+ expect(output).toContain(`"root": __lobeStaticStyle("${runtime.root}"`);
+ expect(output).toContain(`"text-2": __lobeStaticStyle("${runtime['text-2']}"`);
+ });
+
+ it('drops legacy vendor prefixes but keeps the ones Safari still needs', () => {
+ const code = `
+import { createStaticStyles } from 'antd-style';
+export const styles = createStaticStyles(({ css }) => ({
+ root: css\`
+ display: flex;
+ user-select: none;
+ backdrop-filter: blur(4px);
+ transition: opacity 0.2s;
+ -webkit-line-clamp: 2;
+ \`,
+}));
+`;
+ const output = precompileStaticStyles(code, evaluator)!;
+ expect(output).toContain(
+ '{display:flex;-webkit-user-select:none;user-select:none;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);transition:opacity 0.2s;-webkit-line-clamp:2;}',
+ );
+ expect(output).not.toContain('-ms-');
+ expect(output).not.toContain('-webkit-box');
+ });
+
+ it('supports aliased antd-style utils', () => {
+ const code = `
+import { createStaticStyles as make, cssVar as cv } from 'antd-style';
+const styles = make(({ css }) => ({ root: css\`color: \${cv.colorText};\` }));
+`;
+ expect(precompileStaticStyles(code, evaluator)).toContain('color:var(--ant-color-text)');
+ });
+
+ it('leaves callbacks that reference module scope untouched', () => {
+ const code = `
+import { createStaticStyles, cssVar } from 'antd-style';
+const GAP = 8;
+export const styles = createStaticStyles(({ css }) => ({ root: css\`gap: \${GAP}px;\` }));
+`;
+ expect(precompileStaticStyles(code, evaluator)).toBeUndefined();
+ });
+
+ it('leaves callbacks that call runtime helpers untouched', () => {
+ const code = `
+import { createStaticStyles, cssVar } from 'antd-style';
+import { isDesktop } from '@lobechat/const';
+export const styles = createStaticStyles(({ css }) => ({
+ root: css\`padding: \${isDesktop ? 32 : 8}px;\`,
+}));
+`;
+ expect(precompileStaticStyles(code, evaluator)).toBeUndefined();
+ });
+
+ it('compiles pure calls and keeps impure siblings in the same file', () => {
+ const code = `
+import { createStaticStyles, cssVar } from 'antd-style';
+const SIZE = 4;
+export const a = createStaticStyles(({ css }) => ({ root: css\`color: \${cssVar.colorText};\` }));
+export const b = createStaticStyles(({ css }) => ({ root: css\`width: \${SIZE}px;\` }));
+`;
+ const output = precompileStaticStyles(code, evaluator)!;
+ expect(output).toContain('export const a = ({ "root": __lobeStaticStyle(');
+ expect(output).toContain('export const b = createStaticStyles(');
+ });
+
+ it('keeps a bare expression statement syntactically valid', () => {
+ const code = `
+import { createStaticStyles, cssVar } from 'antd-style';
+createStaticStyles(({ css }) => ({ root: css\`color: \${cssVar.colorText};\` }));
+`;
+ const output = precompileStaticStyles(code, evaluator)!;
+ expect(output).toMatch(/\n\(\{ "root": __lobeStaticStyle\(/);
+ expect(() => parseAst(output)).not.toThrow();
+ });
+
+ it('ignores files without an antd-style import', () => {
+ const code = `
+import { createStaticStyles } from './local';
+export const styles = createStaticStyles(({ css }) => ({ root: css\`color: red;\` }));
+`;
+ expect(precompileStaticStyles(code, evaluator)).toBeUndefined();
+ });
+});
+
+describe('insertPrecompiledStyle', () => {
+ it('inserts rules once and exposes emotion-mergeable registered styles', async () => {
+ const { createStaticStyles, css, cx, styleManager } = (await import('antd-style')) as any;
+ const insert = vi.fn();
+ styleManager.cache.sheet = { insert };
+ const rules = ['.acss-fixture{color:red;}', '.acss-fixture:hover{color:blue;}'];
+
+ expect(insertPrecompiledStyle('acss-fixture', rules)).toBe('acss-fixture');
+ insertPrecompiledStyle('acss-fixture', rules);
+ expect(insert.mock.calls.map(([rule]) => rule)).toEqual(rules);
+ expect(styleManager.cache.registered['acss-fixture']).toBe('&{color:red;}&:hover{color:blue;}');
+
+ const merged = cx(
+ 'acss-fixture',
+ css`
+ margin: 0;
+ `,
+ );
+ expect(merged).not.toBe('acss-fixture');
+ expect(styleManager.cache.registered[merged]).toContain('&{color:red;}&:hover{color:blue;}');
+ expect(styleManager.cache.registered[merged]).toContain('margin: 0;');
+
+ const composed = createStaticStyles(({ css: s }: any) => ({
+ x: s`${'acss-fixture'} padding: 0;`,
+ })).x;
+ expect(styleManager.cache.inserted[composed.slice(5)]).toContain(
+ `.${composed}:hover{color:blue;}`,
+ );
+
+ styleManager.cache.registered['acss-fixture'] = 'color: green;';
+ expect(styleManager.cache.registered['acss-fixture']).toBe('color: green;');
+ });
+});
+
+describe('viteStaticStylesPrecompile', () => {
+ const ENTRY_ID = '\0lobe-static-styles-fixture.mjs';
+ const fixturePlugin: Plugin = {
+ load(id) {
+ if (id === ENTRY_ID) return PURE;
+ },
+ name: 'lobe-static-styles-fixture',
+ resolveId(id) {
+ if (id === 'virtual:lobe-static-styles-fixture') return ENTRY_ID;
+ },
+ };
+
+ it('bundles precompiled styles against the antd-style runtime', async () => {
+ const result = await build({
+ build: {
+ minify: false,
+ rolldownOptions: {
+ external: ['antd-style'],
+ input: 'virtual:lobe-static-styles-fixture',
+ },
+ write: false,
+ },
+ configFile: false,
+ logLevel: 'silent',
+ plugins: [fixturePlugin, viteStaticStylesPrecompile()],
+ });
+
+ const outputs = Array.isArray(result) ? result : [result];
+ const code = outputs
+ .flatMap(({ output }) => output)
+ .filter((item) => item.type === 'chunk')
+ .map((item) => item.code)
+ .join('\n');
+
+ expect(code).not.toContain('createStaticStyles');
+ expect(code).toMatch(/import \{ styleManager \} from ["']antd-style["']/);
+ expect(code).toContain('cache.sheet.insert(rule)');
+ expect(code).toContain('color:var(--ant-color-text-secondary)');
+ });
+});
diff --git a/plugins/vite/staticStylesPrecompile.ts b/plugins/vite/staticStylesPrecompile.ts
new file mode 100644
index 00000000000..e983b11ce80
--- /dev/null
+++ b/plugins/vite/staticStylesPrecompile.ts
@@ -0,0 +1,273 @@
+import { readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+
+import { parseAst, type Plugin } from 'vite';
+
+const RUNTIME_ID = 'virtual:lobe-static-styles-runtime';
+const RESOLVED_RUNTIME_ID = `\0${RUNTIME_ID}`;
+const HELPER = '__lobeStaticStyle';
+
+interface AntdStyleEvaluator {
+ cache: {
+ inserted: Record<string, string | true>;
+ key: string;
+ };
+ createStaticStyles: (fn: (utils: unknown) => Record<string, unknown>) => Record<string, unknown>;
+ cssVar: unknown;
+ responsive: unknown;
+}
+
+type Node = { end: number; start: number; type: string } & Record<string, any>;
+
+const STATIC_UTILS = new Set(['cssVar', 'responsive']);
+
+// Safari still needs -webkit- for these; everything else stylis' prefixer adds targets browsers we no longer ship to.
+const WEBKIT_ONLY_PROPS = new Set([
+ 'user-select',
+ 'backdrop-filter',
+ 'hyphens',
+ 'box-decoration-break',
+ 'text-size-adjust',
+]);
+
+const safariPrefixer = (element: {
+ props: unknown;
+ return?: string;
+ type: string;
+ value: string;
+}) => {
+ if (element.type === 'decl' && WEBKIT_ONLY_PROPS.has(element.props as string)) {
+ element.return = `-webkit-${element.value}${element.value}`;
+ }
+};
+
+export const splitRules = (css: string) => {
+ const rules: string[] = [];
+ let depth = 0;
+ let quote: string | undefined;
+ let start = 0;
+ for (let i = 0; i < css.length; i++) {
+ const ch = css[i];
+ if (quote) {
+ if (ch === '\\') i++;
+ else if (ch === quote) quote = undefined;
+ } else if (ch === '"' || ch === "'") quote = ch;
+ else if (ch === '{') depth++;
+ else if (ch === '}' && --depth === 0) {
+ rules.push(css.slice(start, i + 1));
+ start = i + 1;
+ }
+ }
+ if (depth !== 0 || start !== css.length) throw new Error('unbalanced css');
+ return rules;
+};
+
+const walk = (
+ node: Node,
+ visit: (node: Node, parent: Node | undefined) => boolean | void,
+ parent?: Node,
+) => {
+ if (visit(node, parent) === false) return;
+ for (const key of Object.keys(node)) {
+ if (key === 'type' || key === 'start' || key === 'end') continue;
+ const value = node[key];
+ if (Array.isArray(value)) {
+ for (const child of value)
+ if (child && typeof child.type === 'string') walk(child, visit, node);
+ } else if (value && typeof value.type === 'string') walk(value, visit, node);
+ }
+};
+
+const isFunctionNode = (type: string) =>
+ type === 'FunctionDeclaration' ||
+ type === 'FunctionExpression' ||
+ type === 'ArrowFunctionExpression';
+
+const collectAntdStyleImports = (program: Node) => {
+ const locals = new Map<string, string>();
+ for (const statement of program.body as Node[]) {
+ if (statement.type !== 'ImportDeclaration' || statement.source.value !== 'antd-style') continue;
+ for (const specifier of statement.specifiers as Node[]) {
+ if (specifier.type === 'ImportSpecifier')
+ locals.set(specifier.local.name, specifier.imported.name);
+ }
+ }
+ return locals;
+};
+
+const collectPatternNames = (pattern: Node, into: Set<string>) => {
+ if (pattern.type === 'Identifier') into.add(pattern.name);
+ else if (pattern.type === 'ObjectPattern') {
+ for (const property of pattern.properties as Node[]) {
+ collectPatternNames(
+ property.type === 'RestElement' ? property.argument : property.value,
+ into,
+ );
+ }
+ } else if (pattern.type === 'ArrayPattern') {
+ for (const element of pattern.elements as Node[])
+ if (element) collectPatternNames(element, into);
+ } else if (pattern.type === 'AssignmentPattern') collectPatternNames(pattern.left, into);
+ else if (pattern.type === 'RestElement') collectPatternNames(pattern.argument, into);
+};
+
+const isPureCallback = (callback: Node, staticImports: Set<string>) => {
+ const bound = new Set<string>(staticImports);
+ for (const param of callback.params as Node[]) collectPatternNames(param, bound);
+ walk(callback.body, (node) => {
+ if (node.type === 'VariableDeclarator') collectPatternNames(node.id, bound);
+ else if (isFunctionNode(node.type)) {
+ if (node.id) bound.add(node.id.name);
+ for (const param of node.params as Node[]) collectPatternNames(param, bound);
+ }
+ });
+
+ let pure = true;
+ walk(callback.body, (node, parent) => {
+ if (!pure) return false;
+ if (node.type !== 'Identifier') return;
+ if (
+ parent?.type === 'Property' &&
+ !parent.computed &&
+ parent.key === node &&
+ parent.value !== node
+ )
+ return;
+ if (parent?.type === 'MemberExpression' && !parent.computed && parent.property === node) return;
+ if (!bound.has(node.name)) pure = false;
+ });
+ return pure;
+};
+
+const findTopLevelCalls = (program: Node, calleeName: string) => {
+ const calls: Node[] = [];
+ walk(program, (node) => {
+ if (isFunctionNode(node.type)) return false;
+ if (
+ node.type === 'CallExpression' &&
+ node.callee.type === 'Identifier' &&
+ node.callee.name === calleeName &&
+ node.arguments.length === 1 &&
+ isFunctionNode(node.arguments[0].type)
+ ) {
+ calls.push(node);
+ return false;
+ }
+ });
+ return calls;
+};
+
+const evaluate = (
+ callbackSource: string,
+ staticLocals: Map<string, string>,
+ evaluator: AntdStyleEvaluator,
+) => {
+ const names = [...staticLocals.keys()];
+ const values = names.map((name) => evaluator[staticLocals.get(name) as 'cssVar' | 'responsive']);
+
+ const factory = new Function(...names, `return (${callbackSource});`)(...values);
+ return evaluator.createStaticStyles(factory);
+};
+
+const serializeStyles = (result: Record<string, unknown>, evaluator: AntdStyleEvaluator) => {
+ const prefix = `${evaluator.cache.key}-`;
+ const entries: string[] = [];
+ for (const [key, value] of Object.entries(result)) {
+ if (typeof value !== 'string' || !value.startsWith(prefix)) return;
+ const css = evaluator.cache.inserted[value.slice(prefix.length)];
+ if (typeof css !== 'string') return;
+ entries.push(
+ `${JSON.stringify(key)}: ${HELPER}(${JSON.stringify(value)}, ${JSON.stringify(splitRules(css))})`,
+ );
+ }
+ return `({ ${entries.join(', ')} })`;
+};
+
+export const precompileStaticStyles = (code: string, evaluator: AntdStyleEvaluator) => {
+ if (!code.includes('createStaticStyles')) return;
+ let program: Node;
+ try {
+ program = parseAst(code) as unknown as Node;
+ } catch {
+ return;
+ }
+
+ const antdImports = collectAntdStyleImports(program);
+ const calleeName = [...antdImports].find(
+ ([, imported]) => imported === 'createStaticStyles',
+ )?.[0];
+ if (!calleeName) return;
+ const staticLocals = new Map(
+ [...antdImports].filter(([, imported]) => STATIC_UTILS.has(imported)),
+ );
+ const staticNames = new Set(staticLocals.keys());
+
+ const replacements: Array<{ end: number; start: number; text: string }> = [];
+ for (const call of findTopLevelCalls(program, calleeName)) {
+ const callback = call.arguments[0] as Node;
+ if (!isPureCallback(callback, staticNames)) continue;
+ let compiled: string | undefined;
+ try {
+ compiled = serializeStyles(
+ evaluate(code.slice(callback.start, callback.end), staticLocals, evaluator),
+ evaluator,
+ );
+ } catch {
+ continue;
+ }
+ if (compiled) replacements.push({ end: call.end, start: call.start, text: compiled });
+ }
+ if (replacements.length === 0) return;
+
+ let output = code;
+ for (const { start, end, text } of replacements.sort((a, b) => b.start - a.start)) {
+ output = output.slice(0, start) + text + output.slice(end);
+ }
+ return `import { insertPrecompiledStyle as ${HELPER} } from '${RUNTIME_ID}';\n${output}`;
+};
+
+export const loadAntdStyleEvaluator = async (): Promise<AntdStyleEvaluator> => {
+ const mod = await import('antd-style');
+ const api = ((mod as any).default?.createStaticStylesFactory ? (mod as any).default : mod) as any;
+ const antdStyleRequire = createRequire(
+ createRequire(import.meta.url).resolve('antd-style/package.json'),
+ );
+ const createEmotionModule = antdStyleRequire('@emotion/css/create-instance');
+ const createEmotion = createEmotionModule.default ?? createEmotionModule;
+ const emotion = createEmotion({
+ key: api.styleManager.cache.key,
+ stylisPlugins: [safariPrefixer],
+ });
+ const { createStaticStyles, cssVar, responsive } = api.createStaticStylesFactory({
+ cache: emotion.cache,
+ });
+ return { cache: emotion.cache, createStaticStyles, cssVar, responsive };
+};
+
+export function viteStaticStylesPrecompile(): Plugin {
+ let evaluator: Promise<AntdStyleEvaluator> | undefined;
+ return {
+ apply: 'build',
+ enforce: 'post',
+ load(id) {
+ if (id !== RESOLVED_RUNTIME_ID) return;
+ return readFileSync(
+ fileURLToPath(new URL('staticStylesRuntime.js', import.meta.url)),
+ 'utf8',
+ );
+ },
+ name: 'lobe-static-styles-precompile',
+ resolveId(id) {
+ if (id === RUNTIME_ID) return RESOLVED_RUNTIME_ID;
+ },
+ async transform(code, id) {
+ if (!/\.[cm]?[jt]sx?$/.test(id.split('?')[0])) return;
+ if (id.includes('node_modules') && !id.includes('/node_modules/@lobehub/ui/')) return;
+ if (!code.includes('createStaticStyles')) return;
+ evaluator ??= loadAntdStyleEvaluator();
+ const output = precompileStaticStyles(code, await evaluator);
+ if (output) return { code: output, map: null };
+ },
+ };
+}
diff --git a/plugins/vite/staticStylesRuntime.js b/plugins/vite/staticStylesRuntime.js
new file mode 100644
index 00000000000..8eaf3ef195b
--- /dev/null
+++ b/plugins/vite/staticStylesRuntime.js
@@ -0,0 +1,20 @@
+import { styleManager } from 'antd-style';
+
+const cache = styleManager.cache;
+const prefixLength = cache.key.length + 1;
+
+export const insertPrecompiledStyle = (className, rules) => {
+ const name = className.slice(prefixLength);
+ if (cache.inserted[name] === undefined) {
+ for (const rule of rules) cache.sheet.insert(rule);
+ cache.inserted[name] = true;
+ }
+ const define = (descriptor) => Object.defineProperty(cache.registered, className, descriptor);
+ define({
+ configurable: true,
+ enumerable: true,
+ get: () => rules.map((rule) => rule.replaceAll(`.${className}`, '&')).join(''),
+ set: (value) => define({ configurable: true, enumerable: true, value, writable: true }),
+ });
+ return className;
+};