An open source design system that's fully customizable and agent ready
TypeScript
feat: Vite/Storybook prefix separation + consolidate vite-plugin (#1460)
Cindy Zhang98e8ebd27ce5
diff --git a/apps/example-vite/package.json b/apps/example-vite/package.jsonindex 928625f3ca..ad27e5b0d4 100644--- a/apps/example-vite/package.json+++ b/apps/example-vite/package.json@@ -23,7 +23,7 @@"@vitejs/plugin-react": "^4.3.0","typescript": "^5.7.0","vite": "^6.4.2",- "@xds/vite-plugin": "*"+ "@xds/build": "*"},"browserslist": ["last 1 Chrome version"diff --git a/apps/example-vite/vite.config.ts b/apps/example-vite/vite.config.tsindex 712168ab2c..7658e597fa 100644--- a/apps/example-vite/vite.config.ts+++ b/apps/example-vite/vite.config.ts@@ -2,7 +2,7 @@ import path from 'path';import {fileURLToPath} from 'url';import {defineConfig} from 'vite';import react from '@vitejs/plugin-react';-import {xdsStylex} from '@xds/vite-plugin';+import {xdsStylex} from '@xds/build/vite';const __dirname = path.dirname(fileURLToPath(import.meta.url));diff --git a/apps/storybook/.storybook/main.ts b/apps/storybook/.storybook/main.tsindex 5286d400dd..308c6a1f12 100644--- a/apps/storybook/.storybook/main.ts+++ b/apps/storybook/.storybook/main.ts@@ -1,28 +1,9 @@import type {StorybookConfig} from '@storybook/react-vite';-import {xdsStylex} from '@xds/vite-plugin';+import {xdsStylex} from '@xds/build/vite';import path from 'path';const rootDir = path.resolve(__dirname, '../../..');-const coreRoot = path.resolve(__dirname, '../../../packages/core/src');-const themeDefaultRoot = path.resolve(- __dirname,- '../../../packages/themes/default/src/source.ts',-);-const themeNeutralRoot = path.resolve(- __dirname,- '../../../packages/themes/neutral/src/source.ts',-);-const themeBrutalistRoot = path.resolve(- __dirname,- '../../../packages/themes/brutalist/src/source.ts',-);-/**- * Browser targets for lightningcss.- * Prevents lowering native light-dark() into --lightningcss-light/--lightningcss-dark- * polyfill variables. XDS tokens use native light-dark() which is baseline 2024:- * Chrome 123+, Firefox 120+, Safari 17.5+- */const lightningcssTargets = {chrome: 123 << 16,firefox: 120 << 16,@@ -47,7 +28,6 @@ const config: StorybookConfig = {autodocs: 'tag',},viteFinal: async config => {- // Filter out any existing StyleX plugins to avoid conflictsconst filteredPlugins =config.plugins?.filter(plugin =>@@ -101,16 +81,26 @@ const config: StorybookConfig = {targets: lightningcssTargets,},},+ libraryPattern: 'packages/',}),],resolve: {...config.resolve,alias: {...config.resolve?.alias,- '@xds/core': coreRoot,- '@xds/theme-default': themeDefaultRoot,- '@xds/theme-neutral': themeNeutralRoot,- '@xds/theme-brutalist': themeBrutalistRoot,+ '@xds/core': path.resolve(rootDir, 'packages/core/src'),+ '@xds/theme-default': path.resolve(+ rootDir,+ 'packages/themes/default/src/source.ts',+ ),+ '@xds/theme-neutral': path.resolve(+ rootDir,+ 'packages/themes/neutral/src/source.ts',+ ),+ '@xds/theme-brutalist': path.resolve(+ rootDir,+ 'packages/themes/brutalist/src/source.ts',+ ),},},css: {diff --git a/apps/storybook/package.json b/apps/storybook/package.jsonindex 169ad8f346..07bb4c7c27 100644--- a/apps/storybook/package.json+++ b/apps/storybook/package.json@@ -27,6 +27,6 @@"@storybook/test": "^8.6.17","@stylexjs/unplugin": "^0.18.2","storybook": "^8.6.18",- "@xds/vite-plugin": "*"+ "@xds/build": "*"}}diff --git a/eslint.config.js b/eslint.config.jsindex 3b7dcabef1..b538dede96 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -37,7 +37,6 @@ export default tseslint.config("apps/example-nextjs-source/*.js","apps/sandbox/*.js","packages/build/**",- "packages/vite-plugin/**",],},{diff --git a/packages/build/src/vite.ts b/packages/build/src/vite.tsindex 2a04cefe61..7d84bdfb8f 100644--- a/packages/build/src/vite.ts+++ b/packages/build/src/vite.ts@@ -1,6 +1,7 @@import type {Plugin} from 'vite';import stylexBabelPlugin from '@stylexjs/babel-plugin';import stylex from '@stylexjs/unplugin';+import path from 'path';const XDS_LIBRARY_PATTERN = 'node_modules/@xds/';const STYLEX_CSS_PATH = '/virtual:stylex.css';@@ -37,20 +38,10 @@ export interface XDSVitePluginOptions {** reset < xds-base (library) < xds-theme < product (app)*- * Usage:- * import {xdsStylex} from '@xds/vite-plugin';- *- * export default defineConfig({- * plugins: [- * ...xdsStylex({- * stylexOptions: {- * dev: process.env.NODE_ENV === 'development',- * unstable_moduleResolution: { type: 'commonJS', rootDir: __dirname },- * },- * }),- * react(),- * ],- * });+ * The babel wrapper plugin (@xds/build/babel) is injected into the+ * unplugin's babelConfig.plugins so it runs BEFORE the hardcoded+ * StyleX instance. Our wrapper transforms stylex.create() calls with+ * the correct prefix per file, leaving nothing for the stock instance.*/export function xdsStylex(options: XDSVitePluginOptions): Plugin[] {const {@@ -62,10 +53,28 @@ export function xdsStylex(options: XDSVitePluginOptions): Plugin[] {const libraryLayer = layers.library ?? 'xds-base';const productLayer = layers.product ?? 'product';- // Create the base StyleX unplugin with layers enabled+ // Inject our babel wrapper as a user plugin — it runs before the+ // unplugin's hardcoded StyleX instance and handles prefix routing.+ const xdsBabelPlugin = path.resolve(__dirname, 'babel.js');+ const existingPlugins = stylexOptions.babelConfig?.plugins ?? [];+const basePlugin = stylex.vite({...stylexOptions,useCSSLayers: true,+ babelConfig: {+ ...stylexOptions.babelConfig,+ plugins: [+ [+ xdsBabelPlugin,+ {+ ...(stylexOptions as any),+ // Remove babelConfig to avoid circular reference+ babelConfig: undefined,+ },+ ],+ ...existingPlugins,+ ],+ },});// Layer order declaration plugin@@ -88,9 +97,7 @@ export function xdsStylex(options: XDSVitePluginOptions): Plugin[] {configureServer(server) {let stylexPlugin: any = null;- // Return a function so it runs AFTER all configureServer hooksreturn () => {- // Find the stylex pluginfor (const p of server.config.plugins.flat()) {if ((p as any)?.__stylexGetSharedStore) {stylexPlugin = p;@@ -98,7 +105,6 @@ export function xdsStylex(options: XDSVitePluginOptions): Plugin[] {}}- // Prepend our middleware so it runs BEFORE the unplugin'sserver.middlewares.stack.unshift({route: '',handle: (req: any, res: any, next: any) => {diff --git a/packages/vite-plugin/README.md b/packages/vite-plugin/README.mddeleted file mode 100644index 7b13ab4f79..0000000000--- a/packages/vite-plugin/README.md+++ /dev/null@@ -1,92 +0,0 @@-# @xds/vite-plugin--Vite plugin for XDS source builds. Wraps `@stylexjs/unplugin` and splits the compiled CSS into separate named layers so product styles always override library defaults.--## Install--```bash-npm install -D @xds/vite-plugin @stylexjs/unplugin @stylexjs/babel-plugin-```--## Usage--```ts-// vite.config.ts-import {xdsStylex} from '@xds/vite-plugin';-import react from '@vitejs/plugin-react';--export default defineConfig({- plugins: [- ...xdsStylex({- stylexOptions: {- dev: process.env.NODE_ENV === 'development',- runtimeInjection: false,- treeshakeCompensation: true,- unstable_moduleResolution: {- type: 'commonJS',- rootDir: __dirname,- },- },- }),- react(),- ],- resolve: {- alias: {- '@xds/core': path.resolve(__dirname, 'node_modules/@xds/core/src'),- },- },- optimizeDeps: {- exclude: ['@xds/core', '@xds/theme-default'],- },-});-```--## What it does--`xdsStylex()` returns an array of three Vite plugins:--1. **Layer order declaration** — injects `@layer reset, xds-base, xds-theme, product;` into `<head>` before any CSS-2. **StyleX unplugin** — compiles StyleX from both XDS source and product code (delegates to `@stylexjs/unplugin`)-3. **Split-layer interceptor** — intercepts the StyleX CSS endpoint and rewrites the output, partitioning rules by file path into named layers--### Layer ordering--```-reset < xds-base < xds-theme < product-```--- **reset** — XDS reset stylesheet (`@xds/core/reset.css`)-- **xds-base** — XDS component styles (compiled from `node_modules/@xds/`)-- **xds-theme** — Theme overrides (`@xds/theme-default/theme.css`)-- **product** — Your app's StyleX styles (compiled from `src/`)--Product styles always win over XDS defaults without `!important`.--## Options--```ts-interface XDSVitePluginOptions {- /** Options passed to @stylexjs/unplugin */- stylexOptions: StylexUnpluginOptions;-- /** Pattern to identify library files (default: 'node_modules/@xds/') */- libraryPattern?: string;-- /** Layer names */- layers?: {- library?: string; // default: 'xds-base'- product?: string; // default: 'product'- };-}-```--## How it works--The StyleX unplugin collects compiled CSS rules in an internal map keyed by source file path. In dev mode, it serves this CSS via a virtual endpoint (`/virtual:stylex.css`).--This plugin intercepts that endpoint with a middleware that runs before the unplugin's middleware. It reads the same rules map, partitions entries by whether their file path contains `node_modules/@xds/`, processes each group through `stylexBabelPlugin.processStylexRules()` separately, and wraps them in named `@layer` blocks.--## Related--- [`@xds/postcss-plugin`](../postcss-plugin/) — PostCSS plugin for Next.js source builds-- [`@stylexjs/unplugin`](https://github.com/facebook/stylex) — The underlying StyleX compilerdiff --git a/packages/vite-plugin/package.json b/packages/vite-plugin/package.jsondeleted file mode 100644index be964caced..0000000000--- a/packages/vite-plugin/package.json+++ /dev/null@@ -1,27 +0,0 @@-{- "name": "@xds/vite-plugin",- "version": "0.0.1",- "description": "Vite plugin for XDS source builds — wraps @stylexjs/unplugin and splits CSS into library and product layers",- "license": "MIT",- "type": "module",- "main": "src/index.ts",- "exports": {- ".": "./src/index.ts"- },- "files": [- "src"- ],- "keywords": [- "xds",- "vite",- "stylex",- "css-layers",- "design-system"- ],- "peerDependencies": {- "@stylexjs/babel-plugin": ">=0.18.0",- "@stylexjs/unplugin": ">=0.18.0",- "vite": ">=5.0.0"- },- "private": true-}diff --git a/packages/vite-plugin/src/index.ts b/packages/vite-plugin/src/index.tsdeleted file mode 100644index 2a04cefe61..0000000000--- a/packages/vite-plugin/src/index.ts+++ /dev/null@@ -1,165 +0,0 @@-import type {Plugin} from 'vite';-import stylexBabelPlugin from '@stylexjs/babel-plugin';-import stylex from '@stylexjs/unplugin';--const XDS_LIBRARY_PATTERN = 'node_modules/@xds/';-const STYLEX_CSS_PATH = '/virtual:stylex.css';--export interface XDSVitePluginOptions {- /**- * Options passed to @stylexjs/unplugin.- * See https://stylexjs.com/docs/api/configuration/babel-plugin/- */- stylexOptions: Parameters<typeof stylex.vite>[0];-- /**- * Pattern to identify XDS library files vs product files.- * @default 'node_modules/@xds/'- */- libraryPattern?: string;-- /**- * CSS layer names for the split output.- */- layers?: {- /** Layer name for XDS library styles @default 'xds-base' */- library?: string;- /** Layer name for product styles @default 'product' */- product?: string;- };-}--/**- * Vite plugin for XDS source builds.- *- * Wraps @stylexjs/unplugin to compile StyleX from both XDS library source- * and product code, then splits the CSS output into separate named layers:- *- * reset < xds-base (library) < xds-theme < product (app)- *- * Usage:- * import {xdsStylex} from '@xds/vite-plugin';- *- * export default defineConfig({- * plugins: [- * ...xdsStylex({- * stylexOptions: {- * dev: process.env.NODE_ENV === 'development',- * unstable_moduleResolution: { type: 'commonJS', rootDir: __dirname },- * },- * }),- * react(),- * ],- * });- */-export function xdsStylex(options: XDSVitePluginOptions): Plugin[] {- const {- stylexOptions,- libraryPattern = XDS_LIBRARY_PATTERN,- layers = {},- } = options;-- const libraryLayer = layers.library ?? 'xds-base';- const productLayer = layers.product ?? 'product';-- // Create the base StyleX unplugin with layers enabled- const basePlugin = stylex.vite({- ...stylexOptions,- useCSSLayers: true,- });-- // Layer order declaration plugin- const layerOrderPlugin: Plugin = {- name: 'xds-css-layer-order',- transformIndexHtml() {- return [- {- tag: 'style',- children: `@layer reset, ${libraryLayer}, xds-theme, ${productLayer};`,- injectTo: 'head-prepend',- },- ];- },- };-- // Split-layer interceptor plugin- const splitLayerPlugin: Plugin = {- name: 'xds-split-layers',- configureServer(server) {- let stylexPlugin: any = null;-- // Return a function so it runs AFTER all configureServer hooks- return () => {- // Find the stylex plugin- for (const p of server.config.plugins.flat()) {- if ((p as any)?.__stylexGetSharedStore) {- stylexPlugin = p;- break;- }- }-- // Prepend our middleware so it runs BEFORE the unplugin's- server.middlewares.stack.unshift({- route: '',- handle: (req: any, res: any, next: any) => {- if (!req.url?.startsWith(STYLEX_CSS_PATH)) {- return next();- }-- if (!stylexPlugin) {- res.statusCode = 200;- res.setHeader('Content-Type', 'text/css');- res.end('');- return;- }-- const shared = stylexPlugin.__stylexGetSharedStore?.();- const rulesById = shared?.rulesById;-- if (!rulesById || rulesById.size === 0) {- res.statusCode = 200;- res.setHeader('Content-Type', 'text/css');- res.end('');- return;- }-- const libraryRules: any[] = [];- const productRules: any[] = [];-- for (const [filePath, rules] of rulesById.entries()) {- if (filePath.includes(libraryPattern)) {- libraryRules.push(...rules);- } else {- productRules.push(...rules);- }- }-- const libraryCss = libraryRules.length- ? stylexBabelPlugin.processStylexRules(libraryRules, {- useLayers: true,- })- : '';- const productCss = productRules.length- ? stylexBabelPlugin.processStylexRules(productRules, {- useLayers: true,- })- : '';-- const parts: string[] = [];- if (libraryCss)- parts.push(`@layer ${libraryLayer} {\n${libraryCss}\n}`);- if (productCss)- parts.push(`@layer ${productLayer} {\n${productCss}\n}`);-- res.statusCode = 200;- res.setHeader('Content-Type', 'text/css');- res.setHeader('Cache-Control', 'no-store');- res.end(parts.join('\n\n'));- },- });- };- },- };-- return [layerOrderPlugin, basePlugin, splitLayerPlugin];-}