An open source design system that's fully customizable and agent ready
TypeScript
feat: add @xds/vite-plugin + layer demo for example-vite (#1435)
Cindy Zhang51afbb9de22c
diff --git a/apps/example-vite/package.json b/apps/example-vite/package.jsonindex a42b4a78a5..928625f3ca 100644--- a/apps/example-vite/package.json+++ b/apps/example-vite/package.json@@ -22,7 +22,8 @@"@types/react-dom": "^19.2.3","@vitejs/plugin-react": "^4.3.0","typescript": "^5.7.0",- "vite": "^6.4.2"+ "vite": "^6.4.2",+ "@xds/vite-plugin": "*"},"browserslist": ["last 1 Chrome version"diff --git a/apps/example-vite/src/App.tsx b/apps/example-vite/src/App.tsxindex 6d65dadca6..ef0e10670f 100644--- a/apps/example-vite/src/App.tsx+++ b/apps/example-vite/src/App.tsx@@ -21,6 +21,27 @@ const styles = stylex.create({maxWidth: 640,width: '100%',},+ layerDemo: {+ padding: '1.5rem',+ borderRadius: 12,+ backgroundColor: 'var(--color-background-secondary)',+ },+ customButton: {+ borderRadius: 999,+ },+ wideButton: {+ width: '100%',+ },+ brandSecondary: {+ backgroundColor: 'mediumseagreen',+ color: 'white',+ },+ card: {+ borderRadius: 8,+ border: '1px solid var(--color-border)',+ padding: '1rem',+ backgroundColor: 'var(--color-background-body)',+ },});export default function App() {@@ -32,26 +53,93 @@ export default function App() {<div {...stylex.props(styles.container)}><XDSVStack gap={6}><XDSVStack gap={2}>- <XDSHeading level={1}>XDS Example — Vite</XDSHeading>+ <XDSHeading level={1}>XDS Example — Vite (Source)</XDSHeading><XDSText type="body" color="secondary">- This is a reference example for consuming{' '}+ This example compiles{' '}<XDSText type="body" weight="bold">@xds/core</XDSText>{' '}- as a source distribution in a Vite + React application. StyleX- compilation and CSS extraction are handled by{' '}- <XDSText type="body" weight="bold">- @stylexjs/unplugin- </XDSText>{' '}- — no PostCSS or Babel config needed.+ from source with split CSS layers via a Vite middleware that+ intercepts StyleX output.+ </XDSText>+ </XDSVStack>++ <XDSDivider />++ {/* Layer Demo */}+ <XDSVStack gap={3}>+ <XDSHeading level={2}>Layer Demo</XDSHeading>+ <XDSText type="body" color="secondary">+ Product StyleX styles override XDS component defaults via CSS+ layer ordering. No <code>!important</code> needed.</XDSText>++ <div {...stylex.props(styles.layerDemo)}>+ <XDSVStack gap={3}>+ <XDSVStack gap={1}>+ <XDSText type="supporting" weight="bold">+ Default XDS buttons (xds-base layer)+ </XDSText>+ <XDSHStack gap={3} vAlign="center">+ <XDSButton label="Default" variant="primary" />+ <XDSButton label="Default" variant="secondary" />+ </XDSHStack>+ </XDSVStack>++ <XDSVStack gap={1}>+ <XDSText type="supporting" weight="bold">+ Product-styled buttons (product layer overrides)+ </XDSText>+ <XDSHStack gap={3} vAlign="center">+ <XDSButton+ label="Pill shape"+ variant="primary"+ xstyle={styles.customButton}+ />+ <XDSButton+ label="Pill shape"+ variant="secondary"+ xstyle={styles.customButton}+ />+ </XDSHStack>+ </XDSVStack>++ <XDSVStack gap={1}>+ <XDSText type="supporting" weight="bold">+ Three-layer cascade: base → theme → product+ </XDSText>+ <XDSText type="supporting" color="secondary">+ Secondary button background: XDS base → theme override →+ green product override.+ </XDSText>+ <XDSHStack gap={3} vAlign="center">+ <XDSButton label="Theme color" variant="secondary" />+ <XDSButton+ label="Product override"+ variant="secondary"+ xstyle={styles.brandSecondary}+ />+ </XDSHStack>+ </XDSVStack>++ <XDSVStack gap={1}>+ <XDSText type="supporting" weight="bold">+ Full-width product override+ </XDSText>+ <XDSButton+ label="Full width button"+ variant="primary"+ xstyle={styles.wideButton}+ />+ </XDSVStack>+ </XDSVStack>+ </div></XDSVStack><XDSDivider />- {/* Buttons */}<XDSVStack gap={3}>- <XDSHeading level={2}>Buttons</XDSHeading>+ <XDSHeading level={2}>Components</XDSHeading><XDSHStack gap={3} vAlign="center"><XDSButton label="Primary" variant="primary" /><XDSButton label="Secondary" variant="secondary" />@@ -61,7 +149,6 @@ export default function App() {<XDSDivider />- {/* Badges */}<XDSVStack gap={3}><XDSHeading level={2}>Badges</XDSHeading><XDSHStack gap={3} vAlign="center">@@ -74,7 +161,6 @@ export default function App() {<XDSDivider />- {/* Text Input */}<XDSVStack gap={3}><XDSHeading level={2}>Text Input</XDSHeading><XDSTextInput@@ -87,7 +173,21 @@ export default function App() {<XDSDivider />- {/* Typography */}+ <XDSVStack gap={3}>+ <XDSHeading level={2}>Source Build</XDSHeading>+ <div {...stylex.props(styles.card)}>+ <XDSText type="body">+ Open devtools → inspect the CSS layers panel. You'll see{' '}+ <code>@layer xds-base</code> and <code>@layer product</code>.+ The layer order{' '}+ <code>reset < xds-base < xds-theme < product</code>{' '}+ ensures product styles always win.+ </XDSText>+ </div>+ </XDSVStack>++ <XDSDivider />+<XDSVStack gap={3}><XDSHeading level={2}>Typography</XDSHeading><XDSText type="large" weight="bold">diff --git a/apps/example-vite/vite.config.ts b/apps/example-vite/vite.config.tsindex 04af39b787..712168ab2c 100644--- a/apps/example-vite/vite.config.ts+++ b/apps/example-vite/vite.config.ts@@ -2,17 +2,13 @@ import path from 'path';import {fileURLToPath} from 'url';import {defineConfig} from 'vite';import react from '@vitejs/plugin-react';-import stylex from '@stylexjs/unplugin';+import {xdsStylex} from '@xds/vite-plugin';const __dirname = path.dirname(fileURLToPath(import.meta.url));/*** 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+- *- * Must match the targets in apps/storybook/.storybook/main.ts+ * Prevents lowering native light-dark() into polyfill variables.*/const lightningcssTargets = {chrome: 123 << 16,@@ -20,44 +16,26 @@ const lightningcssTargets = {safari: (17 << 16) | (5 << 8),};-// https://vite.dev/config/export default defineConfig({plugins: [- // Declare CSS layer order. xds-theme is last (highest priority among- // declared layers) so theme component overrides beat StyleX styles.- // Prose defaults inject into @layer reset (lowest priority).- {- name: 'xds-css-layer-order',- transformIndexHtml() {- return [- {- tag: 'style',- children:- '@layer reset, priority1, priority2, priority3, priority4, priority5, priority6, priority7, priority8, priority9, xds-theme;',- injectTo: 'head-prepend',- },- ];- },- },- stylex.vite({- dev: process.env.NODE_ENV === 'development',- runtimeInjection: false,- treeshakeCompensation: true,- useCSSLayers: true,- unstable_moduleResolution: {- type: 'commonJS',- rootDir: __dirname,- },- lightningcssOptions: {- targets: lightningcssTargets,+ ...xdsStylex({+ stylexOptions: {+ dev: process.env.NODE_ENV === 'development',+ runtimeInjection: false,+ treeshakeCompensation: true,+ unstable_moduleResolution: {+ type: 'commonJS',+ rootDir: __dirname,+ },+ lightningcssOptions: {+ targets: lightningcssTargets,+ },},}),react(),],resolve: {alias: {- // Alias @xds/core subpaths to source files so Vite compiles them- // from TypeScript source rather than requiring a pre-built dist/.'@xds/core/theme/tokens.stylex': path.resolve(__dirname,'node_modules/@xds/core/src/theme/tokens.stylex.ts',@@ -65,9 +43,6 @@ export default defineConfig({'@xds/core': path.resolve(__dirname, 'node_modules/@xds/core/src'),},},- // Prevent Vite from pre-bundling XDS with esbuild. XDS ships as source- // that must be compiled by the StyleX plugin — pre-bundling strips the- // stylex.create/defineVars calls and causes a runtime error.optimizeDeps: {exclude: ['@xds/core', '@xds/theme-default'],},diff --git a/eslint.config.js b/eslint.config.jsindex a150fc48aa..686d4c81cc 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -37,6 +37,7 @@ export default tseslint.config("apps/example-nextjs-source/*.js","apps/sandbox/*.js","packages/postcss-plugin/**",+ "packages/vite-plugin/**",],},{diff --git a/packages/postcss-plugin/README.md b/packages/postcss-plugin/README.mdnew file mode 100644index 0000000000..ba0b416451--- /dev/null+++ b/packages/postcss-plugin/README.md@@ -0,0 +1,112 @@+# @xds/postcss-plugin++PostCSS plugin for XDS source builds. Compiles StyleX from both XDS library source and product code, then splits the output into separate CSS layers.++## Install++```bash+npm install -D @xds/postcss-plugin @stylexjs/babel-plugin @babel/core+```++## Usage++```js+// babel.config.js+const path = require('path');++module.exports = {+ presets: ['next/babel'],+ plugins: [+ [+ '@stylexjs/babel-plugin',+ {+ dev: process.env.NODE_ENV !== 'production',+ runtimeInjection: false,+ enableInlinedConditionalMerge: true,+ treeshakeCompensation: true,+ aliases: {+ '@xds/core/*': [path.join(__dirname, 'node_modules/@xds/core/*')],+ '@xds/core': [path.join(__dirname, 'node_modules/@xds/core')],+ },+ unstable_moduleResolution: {type: 'commonJS'},+ },+ ],+ ],+};+```++```js+// postcss.config.js+const babelConfig = require('./babel.config');++module.exports = {+ plugins: {+ '@xds/postcss-plugin': {+ appDir: 'src',+ babelPlugins: babelConfig.plugins,+ },+ },+};+```++```css+/* globals.css */+@import './layers.css';+@import '@xds/core/reset.css';+@import '@xds/theme-default/theme.css';++@stylex;+```++```css+/* layers.css */+@layer reset, xds-base, xds-theme, product;+```++## What it does++The plugin scans both your app source and `node_modules/@xds/` for StyleX usage. It compiles everything in a single pass using the Babel plugin, then partitions the resulting CSS rules by file path:++- Rules from `node_modules/@xds/` → `@layer xds-base`+- Rules from your app source → `@layer product`++### Layer ordering++```+reset < xds-base < xds-theme < product+```++Product styles always win over XDS defaults without `!important`.++## Options++```ts+{+ /** Directory containing your app source (default: 'src') */+ appDir?: string;++ /** StyleX babel plugins from your babel.config.js */+ babelPlugins?: any[];++ /** Layer names (override if needed) */+ layers?: {+ library?: string; // default: 'xds-base'+ product?: string; // default: 'product'+ };++ /** Additional include globs beyond appDir and @xds packages */+ extraInclude?: string[];++ /** Exclude globs */+ exclude?: string[];+}+```++## Why a separate `layers.css` file?++The `@layer` order declaration must appear before any layer content in the CSS output. In Next.js, webpack hoists `@import` content above inline CSS in the same file, so an inline `@layer` statement in `globals.css` would appear _after_ `reset.css` and `theme.css` content. A separate `layers.css` file imported first ensures correct ordering.++## Related++- [`@xds/vite-plugin`](../vite-plugin/) — Vite plugin for source builds+- [example-nextjs-source](../../apps/example-nextjs-source/) — Full Next.js source build examplediff --git a/packages/postcss-plugin/package.json b/packages/postcss-plugin/package.jsonindex 76f69389e0..f08028a24d 100644--- a/packages/postcss-plugin/package.json+++ b/packages/postcss-plugin/package.json@@ -1,7 +1,7 @@{"name": "@xds/postcss-plugin","version": "0.0.1",- "description": "PostCSS plugin for XDS source builds \u2014 splits StyleX output into library and product CSS layers",+ "description": "PostCSS plugin for XDS source builds — splits StyleX output into library and product CSS layers","license": "MIT","main": "src/index.js","exports": {diff --git a/packages/vite-plugin/README.md b/packages/vite-plugin/README.mdnew file mode 100644index 0000000000..7b13ab4f79--- /dev/null+++ b/packages/vite-plugin/README.md@@ -0,0 +1,92 @@+# @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.jsonnew file mode 100644index 0000000000..be964caced--- /dev/null+++ b/packages/vite-plugin/package.json@@ -0,0 +1,27 @@+{+ "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.tsnew file mode 100644index 0000000000..2a04cefe61--- /dev/null+++ b/packages/vite-plugin/src/index.ts@@ -0,0 +1,165 @@+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];+}