The user wants a comprehensive migration guide/example from a CSS-in-JS library (like styled-components or Emotion) to vanilla-extract.
Key areas to highlight:
Tree-shaking benefits: How vanilla-extract's zero-runtime nature helps with bundle size compared to runtime CSS-in-JS.
Theme token alignment: How to handle theming using createThemeContract and createTheme vs the typical React Context approach.
SSR compatibility: How vanilla-extract avoids the pitfalls of hydration mismatches and style injection timing issues common in runtime solutions.
Plan:
Introduction: Briefly define the scenario (moving from a runtime solution like Styled-Components/Emotion).
Phase 1: The "Before" State (Runtime CSS-in-JS):
Show a typical React component using a runtime library.
Show how theming is usually done (ThemeProvider).
Point out the drawbacks (runtime cost, bundle size inclusion of the library).
Phase 2: The "After" State (Vanilla-Extract):
Show the .css.ts file structure.
Demonstrate the component usage (using classNames).
Phase 3: Deep Dive into Key Areas:
Tree-shaking: Explain why unused styles are removed and the runtime library code disappears.
Theme Token Alignment: Show createThemeContract. This is crucial for type-safe theming across multiple themes.
SSR Compatibility: Explain the "zero-runtime" concept. Styles are generated at build time, so no flash of unstyled content (FOUC) or hydration mismatches.
Code Examples: specific code snippets for each step.
Summary/Benefits: Recap.
Drafting the Content - Technical Details:
Scenario: A simple Button component.
Migration Steps:
Define the contract (interface for the theme).
Define the actual themes (Light/Dark).
Define styles (style function).
Variants (styleVariants).
Addressing Specific Requirements:
Tree-shaking: Vanilla-extract outputs static CSS files (or virtual modules). Since logic runs at build time, the final JS bundle doesn't need the styling engine. This is the ultimate "tree-shake" – the whole tree of the styling library is gone from the client bundle.
Theme Token Alignment: In styled-components, you might do props => props.theme.colors.primary. In VE, you define a contract. This ensures that if you switch themes, the variable names must match. This provides type safety.
SSR: Since styles are just CSS strings or class names at runtime, React renders a string with class names. No useInsertionEffect or style injection logic runs on the server, preventing the common "UI flash" or complex stream injection logic required by Emotion v11+.
Refining the Code Structure:
Input: Button.tsx (styled-components).
Output: Button.css.ts + Button.tsx.
Self-Correction/Refinement during thought process:
Tree-shaking note: I need to be careful not to say "it tree-shakes unused CSS" (though it does via PurgeCSS usually attached to the build), but the main benefit compared to runtime libraries is removing the runtime library itself from the bundle.
Theming: VE uses CSS variables for theming. This is the key to its SSR performance. I should explicitly show how the contract maps to CSS variables.
Final Structure of the response:
High-Level Architecture: Diagram or text explaining the shift from Runtime -> Build Time.
Step 1: Defining the Theme Contract (The "Alignment"): Code showing createThemeContract.
Step 2: Implementing Themes (The Variables): Code showing createTheme.
Step 3: Component Styles: Code showing style and usage of theme vars.
Step 4: Integration: React component.
Analysis: Detailed comparison of Tree-shaking, Tokens, and SSR.
This looks solid. I will proceed with generating the detailed response based on this structure.
This migration plan outlines the transition from a runtime CSS-in-JS library (like styled-components or @emotion) to vanilla-extract.
This guide focuses on a Button component migration to demonstrate the architectural shift from runtime injection to build-time static analysis.
1. The Strategy: Runtime vs. Build Time
The core philosophy of this migration is moving logic out of the browser.
Current State (Runtime): The browser downloads a JS bundle, parses it, executes logic to generate CSS strings, and injects them into a <style> tag. This costs CPU cycles and causes hydration mismatches.
Target State (Build Time):vanilla-extract runs during the Webpack/Vite/Esbuild compilation step. It generates static .css files. The browser downloads pre-compiled CSS and applies it immediately.
2. Phase I: Theme Token Alignment
In runtime CSS-in-JS, themes are often JavaScript objects accessed via React Context. In vanilla-extract, themes are CSS Custom Properties (Variables) generated at build time. This alignment ensures type safety without runtime overhead.
styles/themes.css.ts
We define a "contract" (the interface) and the implementation (the values). This allows for type-safe theming (e.g., Light/Dark mode) without JS logic.
typescript
import { createThemeContract, createTheme } from '@vanilla-extract/css';
// 1. The Contract: Defines the shape of your tokens (The API)
// This replaces the TypeScript interface of your old JS theme.
export const vars = createThemeContract({
color: {
primary: null,
background: null,
text: null,
},
space: {
small: null,
medium: null,
},
font: {
body: null,
}
});
// 2. The Implementation: Assigns values to the contract
export const lightTheme = createTheme(vars, {
color: {
primary: '#0070f3',
background: '#ffffff',
text: '#000000',
},
space: {
small: '4px',
medium: '16px',
},
font: {
body: 'system-ui, sans-serif',
},
});
export const darkTheme = createTheme(vars, {
color: {
primary: '#58a6ff',
background: '#0d1117',
text: '#c9d1d9',
},
space: {
small: '4px',
medium: '16px',
},
font: {
body: 'system-ui, sans-serif',
},
});
3. Phase II: Component Migration
We move styles out of the component file (.tsx) into a dedicated style file (.css.ts).
The "Before" (e.g., Styled Components)
Note the dynamic logic based on props inside the JS runtime.
We use recipe (from @vanilla-extract/recipes) to handle variants (props) statically.
Button.css.ts
typescript
import { style, createVar } from '@vanilla-extract/css';
import { recipe } from '@vanilla-extract/recipes';
import { vars } from './themes.css';
// Recipes allow us to map props (variants) to specific styles at build time
export const buttonRecipe = recipe({
base: {
// Consuming the token defined in Phase I
backgroundColor: vars.color.primary,
fontFamily: vars.font.body,
border: 'none',
cursor: 'pointer',
transition: 'opacity 0.2s ease',
selectors: {
'&:hover': {
opacity: 0.9,
},
},
},
variants: {
size: {
small: {
padding: vars.space.small,
},
large: {
padding: vars.space.medium,
},
},
outlined: {
true: {
background: 'transparent',
border: `1px solid ${vars.color.primary}`,
color: vars.color.primary,
},
false: {},
},
},
defaultVariants: {
size: 'small',
}
});
Button.tsx
The component becomes a simple glue layer.
tsx
import { buttonRecipe } from './Button.css';
import { lightTheme, darkTheme } from './styles/themes.css';
interface ButtonProps {
size?: 'small' | 'large';
outlined?: boolean;
theme?: 'light' | 'dark';
children: React.ReactNode;
}
export const Button = ({
size,
outlined,
theme = 'light',
children
}: ButtonProps) => {
// We apply the theme class to scope the CSS variables
const themeClass = theme === 'dark' ? darkTheme : lightTheme;
return (
<div className={themeClass}>
<button
className={buttonRecipe({ size, outlined })}
>
{children}
</button>
</div>
);
};
4. Phase III: The Benefits Realized
A. Tree Shaking (Dead Code Elimination)
In standard CSS-in-JS, your main bundle includes the entire styling engine (approx. 10-15KB minified) plus the logic for every style definition.
With Vanilla Extract:
Zero Runtime: The vanilla-extract library is a devDependency. It does not exist in your production JS bundle.
Recipe Optimization: If you define a button variant variant: { huge: { ... } } but never use it in your codebase, modern bundlers can often prune the CSS associated with unused variants (depending on setup), or at the very least, the CSS is compressed into a static string, removing the execution cost of generating it on the client.
B. Theme Token Alignment
By using createThemeContract, we enforce strict type safety between design tokens and component usage.
Problem in Runtime: Changing theme.colors.primary to theme.palette.primary breaks the app at runtime (you see white text on white background or error boundaries).
Solution in VE: This breaks the build. TypeScript will throw an error in the CI/CD pipeline if vars.color.primary is referenced but does not exist in the active contract.
C. SSR (Server-Side Rendering) Compatibility
Runtime CSS-in-JS faces significant challenges in SSR (Next.js, Remix):
The FOUC (Flash of Unstyled Content): The server sends HTML. The browser renders it. Then the JS loads, parses styles, and injects tags, causing a visual shift.
Hydration Mismatches: Generating unique class names on the server vs. the client requires complex state synchronization.
Vanilla Extract Solution:
Static Extraction: Styles are extracted into .css files during the build process.
Link Tags: The SSR output simply includes a standard <link rel="stylesheet" href="styles.css">.
Result: The browser receives the CSS before React hydrates. The page is visually perfect immediately, improving Core Web Vitals (CLS - Cumulative Layout Shift).