The user wants to know how to plan a migration from CSS variables (Custom Properties) to design tokens managed by Style Dictionary, specifically keeping the ability to override these values at runtime (in the browser).
Key Concepts & Technologies:
CSS Variables (Custom Properties):--color-primary: blue;. Highly dynamic, changeable in JS or CSS at runtime.
Design Tokens: The single source of truth (usually JSON) for design decisions.
Style Dictionary: A tool that transforms tokens into platform-specific formats (CSS, SCSS, JS, iOS, Android, etc.).
Runtime Overrides: The ability to change a value while the app is running (e.g., switching themes, user preferences) without rebuilding.
The Challenge:
A naive implementation of Design Tokens often results in "hardcoded" values (e.g., color: #0000FF;) or pre-compiled variables (SCSS $color-primary). These don't support runtime changes. CSS variables do support runtime changes.
Therefore, the migration strategy isn't just "delete CSS, add Style Dictionary." It is "Generate CSS Variables from Style Dictionary."
Migration Steps/Strategy:
Audit: What exists right now? (CSS files, variable usage).
Setup Style Dictionary: Initialize the project structure.
Token Definition: Map existing CSS variables to JSON/YAML tokens.
Configuration: Configure Style Dictionary to output CSS variables (the css/variables format).
Implementation/Runtime Strategy: How to keep the overrides?
Option A: Output standard :root variables. This maintains the override capability.
Option B: "References" approach. The tokens are semantic, but the CSS variables are the implementation layer.
The "Runtime Override" specific architecture:
Style Dictionary builds the default theme.
If users need overrides, they modify the CSS variables in the DOM (JavaScript).
Crucial: Ensure the build process doesn't "bake in" values (like replacing var(--token) with hex codes during build) if dynamic changes are needed in non-CSS contexts (like canvas or SVGs sometimes, though CSS variables work fine for CSS).
Refining the "Runtime Overrides" Aspect:
The user explicitly asked to maintain runtime overrides.
Current state:--my-var: value; (can be changed in JS).
Target state: Style Dictionary generates --my-var: value; (still can be changed in JS).
Advanced scenario: Maybe they mean updating the token definitions at runtime? No, usually "runtime overrides" means theming or CSS variable manipulation.
Alias/Reference pattern: It's often good to separate "Primitive" tokens (raw values) from "Semantic/Alias" tokens (how they are used). This makes theming easier.
Drafting the Plan:
Phase 1: Foundation & Audit (The "As-Is" State)
Inventory current CSS vars.
Categorize (Global vs Component vs Semantic).
Phase 2: Style Dictionary Setup (The "To-Be" Tooling)
Install.
Structure folders (tokens/, dist/).
Phase 3: Migration Strategy (The "How")
Approach: Map CSS vars to JSON properties.
Key Technique: Use the css/variables format in Style Dictionary. This outputs --name: value;.
Aliases: Create a tiered structure (Global -> Alias -> Component) to make future theming easier.
Phase 4: Runtime Overrides (The Specific Requirement)
Mechanism: Style Dictionary generates the definitions. The browser still interprets var(--token).
Theming: How to handle multiple themes? Style Dictionary can generate multiple CSS files (theme-light.css, theme-dark.css) that override :root or a class selector.
JavaScript Integration: Provide a way to bridge tokens to JS if needed (e.g., formatTokens for JSON output to JS), but rely on CSS variables for styling.
Phase 5: Execution & Validation
Run build.
Replace manual CSS vars with the generated file.
Test overrides.
Specific "Gotchas" / Nuances:
Naming collisions: Ensure JSON keys map to valid CSS variable names (usually handled by SD transforms).
Composite tokens: Borders, shadows, typography. Style Dictionary handles these well, but need custom formats if the default CSS output isn't enough (e.g., decomposing a "shadow" token into individual CSS vars vs a string).
Theming architecture: The "W3C Design Tokens" spec is emerging. Style Dictionary supports it via community plugins or the upcoming v4 native support. I should stick to standard SD practices for now but mention semantic layers.
Self-Correction during thought process:
Initial thought: Should I suggest CSS-in-JS?
Correction: No, stick to the prompt. The prompt is about migrating from CSS vars. The best way to keep runtime overrides is to keep using CSS vars, just generate them via SD.
Refinement: Make sure to distinguish between "changing a token in code and rebuilding" vs "changing a value in the browser at runtime." The prompt asks for runtime overrides. This means the output must be standard CSS Custom Properties.
Detailed Plan Structure:
Architecture Overview: Explain how SD generates CSS vars.
Step 1: Inventory & Organization: JSON structure.
Step 2: Configuration (style-dictionary.js): The css/variables format.
Step 3: The Runtime Strategy: Namespacing and Theming.
Step 4: Handling References/Aliases: The key to robust overrides.
Step 5: Build & Integration.
Example Code:
Need to show:
Input: tokens.json
Config: style-dictionary.js
Output: variables.css
Addressing "Runtime Overrides" specifically:
I need to explain how the override happens.
Default: :root { --color-primary: #000; }
Override: html[data-theme="dark"] { --color-primary: #FFF; }
Style Dictionary can actually generate both of these if set up correctly (using file headers or separate configs), or just the base, and manual overrides happen downstream.
Actually, the most robust way with SD is having semantic tokens (e.g., bg-color) that reference global tokens (grey-100).
To support runtime overrides without a full rebuild, we rely on the browser's cascade.
However, if the user wants to inject new tokens at runtime, that's standard JS.
If the user wants to switch themes defined in SD, SD generates the theme CSS files.
Let's stick to the most common interpretation: Using Style Dictionary to generate the CSS Custom Properties file, preserving the dynamic nature of CSS Custom Properties.
Structure of the response:
The Core Concept: SD generates the static definition file; CSS Custom Properties handle the dynamic runtime behavior.
Phase 1: Inventory & Structure.
Phase 2: The Token Architecture (Semantic vs Global). Essential for overrides.
Let's refine the "Runtime" part.
The "Token" is the source of truth.
The "CSS Variable" is the implementation.
To override at runtime, you change the CSS Variable in the DOM (e.g., document.documentElement.style.setProperty('--my-token', 'new-value')).
The migration plan must ensure the naming convention is stable and predictable.
Final check of the prompt: "Plan a migration..."
Okay, I will structure it as a step-by-step migration plan.
Step 1: Extract. Convert existing vars to JSON.
Step 2: Configure. Set up SD to output :root.
Step 3: Implement. Swap manual file for generated file.
Step 4: Advanced Runtime. Multi-theme generation.
I will emphasize the "Semantic Layer" strategy.
Primitive:blue-500
Semantic:primary-action -> blue-500
Runtime Override: Change primary-action to green-500 dynamically.
By enforcing the semantic layer in the SD setup, runtime overrides make sense (changing the meaning, not the raw color).
Let's write the response.
Transitioning from hardcoded CSS variables to Style Dictionary involves moving your source of truth from CSS files to JSON/YAML files.
To maintain runtime overrides (e.g., switching themes without reloading the page or rebuilding the app), you must ensure that Style Dictionary outputs CSS Custom Properties (Variables) rather than static values (like HEX codes).
Here is a comprehensive migration plan to implement Design Tokens while preserving dynamic theming capabilities.
Phase 1: Architecture & Strategy
The core strategy is the "Semantic Layer" approach.
Source of Truth: JSON files defining global primitives (colors, spacing) and semantic aliases (background-primary, text-error).
Build Output: A single CSS file containing :root declarations.
Runtime: JavaScript updates the style attribute of the <html> element to override specific variables.
The Token Hierarchy
To support overrides, your tokens should be structured in layers:
Global/Primitive: Raw values (e.g., color.blue.500: #0000FF).
Semantic/Alias: Context-specific names (e.g., color.background.primary: {color.blue.500}). This is what your components use.
Component: Specific usage (e.g., button.background: {color.background.primary}).
Why this matters: At runtime, you override the Semantic token, not the Global one. This ensures that changing "Primary Background" updates every component using it, without breaking the raw color palette.
Phase 2: The Migration Plan (Step-by-Step)
Step 1: Inventory & Cleanup
Before writing JSON, audit your current CSS variables.
Find all CSS Custom Properties (--*) in your codebase.
Identify "dead" variables that are defined but never used.
Group them into categories: color, spacing, typography, elevation, radii.
Step 2: Setup Style Dictionary
Initialize the project structure.
npm install style-dictionary --save-dev
Directory Structure:
src/
tokens/ # JSON Source of Truth
global.json # Primitives (raw colors, sizes)
semantic.json # Aliases (background, text, border)
components/ # Your app code
style-dictionary.config.js
Step 3: Define Tokens (JSON)
Translate your cleaned-up CSS variables into JSON.
Step 4: Configure Style Dictionary for CSS Variables
Configure the build to output CSS custom properties. This preserves runtime capabilities.
style-dictionary.config.js
module.exports = {
source: ["src/tokens/**/*.json"],
platforms: {
css: {
transformGroup: "css",
buildPath: "src/css/",
files: [{
destination: "variables.css",
format: "css/variables",
options: {
outputReferences: true // Keeps the link between semantic and global
}
}]
}
}
};
Run the build: npx style-dictionary build.
Output (src/css/variables.css):
:root {
/* Colors */
--color-blue-500: #0000FF;
--color-red-500: #FF0000;
/* Semantic Aliases - These are what you override */
--background-primary: var(--color-blue-500);
--background-error: var(--color-red-500);
}
Step 5: Integration & Consumption
Import the CSS: Import the generated variables.css into your main entry point (e.g., index.js or App.jsx).
Update Code: Ensure your application code uses the Semantic tokens, not the global ones.
Bad:background: var(--color-blue-500);
Good:background: var(--background-primary);
Phase 3: Implementing Runtime Overrides
Since you are using CSS Custom Properties, you can override them using standard JavaScript. You do not need a specific library to "apply" the tokens; you just change the CSS variable on the root.
Scenario: Switching to "Dark Mode" or "Client Branding"
1. The CSS Strategy (Theme Files)
If you have predefined themes (e.g., Light/Dark), use Style Dictionary to generate separate CSS files for each theme context.
Updated Config:
// style-dictionary.config.js
// ... setup for "light" and "dark" token sets
2. The Runtime JavaScript Strategy
If you fetch theme settings from an API (e.g., user prefers high contrast or specific brand color):
// themeManager.js
export const applyTheme = (themeObject) => {
const root = document.documentElement;
// Iterate over the theme object and update CSS variables
// themeObject example: { "background-primary": "#FF0000", "spacing-sm": "12px" }
Object.entries(themeObject).forEach(([key, value]) => {
// Convert camelCase/json name to CSS variable name (e.g. backgroundPrimary -> --background-primary)
const cssVarName = `--${key.replace(/([A-Z])/g, '-$1').toLowerCase()}`;
// Update the variable on :root
root.style.setProperty(cssVarName, value);
});
};
Handling "Complex" Tokens (Typography, Shadows)
CSS Variables can only hold simple strings. You cannot easily put a complex object (like a full typography definition) into a single variable.
Solution:
Don't try to make --font-heading hold "Weight 700, Size 24px". Instead, output Utility Classes or Mixins from Style Dictionary, and use CSS Variables only for the specific parameters (size, weight, family).