Multi-Brand Theming Integration Plan
This plan outlines a scalable, type-safe system for multi-brand theming using design tokens, CSS custom properties (variables), and compile-time guardrails. It supports dynamic runtime switching (e.g., via user selection or A/B testing) while enforcing consistency and preventing invalid configurations.
Assumptions:
- Modern frontend stack (e.g., React/Vue/Svelte with Vite/Webpack).
- Brands: e.g., "BrandA" (primary blue theme), "BrandB" (warm red theme).
- Tools: Style Dictionary (for token transformation), TypeScript (for guardrails), PostCSS/Vite for CSS processing.
1. Architecture Overview
Source Tokens (JSON/TS) → Build Pipeline → Outputs
├── Design Tokens (per-brand JSON)
│ ├── BrandA/tokens.json
│ └── BrandB/tokens.json
├── Build (Style Dictionary + Custom Scripts)
│ ├── CSS Vars (.brand-a {}, .brand-b {})
│ ├── TypeScript Types (token.d.ts)
│ └── JS Runtime Utils (switchTheme(brand))
└── Runtime
├── Class-based switching (.brand-{id} on <html>)
└── Type-safe usage (e.g., `color: var(--color-primary)` + TS checks)
- Runtime Switching: Apply classes to
<html> (e.g., document.documentElement.classList.add('brand-a')).
- Fallbacks: CSS vars cascade with defaults.
- Scalability: Add new brands by dropping a
tokens.json; build auto-generates everything.
2. Design Token Structure
Use a semantic, nested JSON format (Figma/ZeroHeight-inspired). Core categories: color, spacing, typography, radius, shadows.
Example: tokens/BrandA/tokens.json
{
"$brand": "BrandA",
"color": {
"primary": { "value": "#007BFF" },
"primary-50": { "value": "#E3F2FD" },
"background": { "value": "#FFFFFF" }
},
"spacing": {
"xs": { "value": "0.25rem" },
"s": { "value": "0.5rem" }
},
"font": {
"family": { "value": "'Inter', sans-serif" },
"size": {
"base": { "value": "1rem" }
}
}
}
Global Tokens (tokens/global.json): Shared defaults (e.g., spacing scales).
- Aliases: Reference sematics, e.g.,
"primary-button-bg": { "value": "{color.primary.value}" }.
Validation Schema (JSON Schema): Define required structure in token-schema.json for build-time checks.
3. Build Pipeline
Use npm scripts with Style Dictionary + custom plugins.
package.json scripts:
{
"scripts": {
"tokens:build": "style-dictionary build --config style-dictionary.config.js",
"tokens:validate": "ajv validate -s token-schema.json -d 'tokens/**/*.json'",
"tokens:types": "style-dictionary build --config ts-config.js"
}
}
Style Dictionary Config (style-dictionary.config.js):
const StyleDictionary = require('style-dictionary');
StyleDictionary.extend({
source: ['tokens/global.json', 'tokens/Brand*/tokens.json'],
platforms: {
css: {
transformGroup: 'css',
buildPath: 'dist/css/',
files: [{
destination: 'themes.css',
format: 'css/variables',
options: {
outputReferences: true, // Preserve aliases
selector: '.brand-{brand}' // Per-brand :root
}
}]
},
ts: {
transformGroup: 'typescript',
buildPath: 'dist/types/',
files: [{ destination: 'tokens.d.ts', format: 'typescript/declarations' }]
}
}
}).buildAllPlatforms();
Outputs:
.brand-a {
--color-primary: #007BFF;
--spacing-xs: 0.25rem;
/* ... */
}
.brand-b {
--color-primary: #FF4500;
/* ... */
}
:root { /* Global defaults */ }
export type Brand = 'BrandA' | 'BrandB';
export interface Tokens {
color: { primary: string; /* ... */ };
// IntelliSense everywhere
}
export const TOKENS: Record<Brand, Tokens>;
PostCSS Plugin: Auto-inject themes.css into your bundle.
4. Runtime Implementation
Theme Switcher JS (src/utils/theme.ts):
// Type-safe from build output
import type { Brand, Tokens } from '../../dist/types/tokens.d.ts';
import TOKENS from '../../dist/types/tokens.json'; // Optional runtime lookup
const BRANDS: Brand[] = ['BrandA', 'BrandB'];
export function switchTheme(brand: Brand): void {
if (!BRANDS.includes(brand)) throw new Error(`Invalid brand: ${brand}`);
document.documentElement.className = `brand-${brand}`;
}
// Persist in localStorage + init on load
export function initTheme(defaultBrand: Brand = 'BrandA'): void {
const saved = localStorage.getItem('theme') as Brand | null;
switchTheme(saved || defaultBrand);
}
Usage in Components (React example):
<button style={{ backgroundColor: 'var(--color-primary)', padding: 'var(--spacing-m)' }}>
Button
</button>
- TS enforces var names via generated types (e.g., ESLint plugin or VSCode snippets).
SSR/CSR Hydration: Use <html class="brand-a"> server-side; client-side sync.
5. Compile-Time Guardrails
Prevent misuse pre-runtime:
| Guardrail | Tool/Method | Benefit |
|---|
| Token Validation | AJV + JSON Schema | Ensures required tokens exist, values are valid (e.g., hex colors). Fail build on mismatch. |
| Type Generation | Style Dictionary TS transform | Full IntelliSense/type-checking for var(--token-name). |
| CSS Var Naming | PostCSS stylelint + custom rule | Enforce --{category}-{name} prefix. No magic strings. |
| Brand Exhaustiveness | TS union + ESLint no-restricted-syntax | switchTheme('Invalid') → compile error. |
| Alias Resolution | Style Dictionary references | Build resolves {color.primary} → inline value + type. |
| Deprecation | Token metadata ($deprecated: true) | Warn in build/IDE. |
| CI/CD Check | Husky pre-commit + Vitest | Run npm run tokens:validate before push. |
ESLint Rule Example (.eslintrc):
{
"rules": {
"token-vars-only": ["error", { "pattern": "^var\\(--[a-z-]+\\)$" }]
}
}
6. Testing & Maintenance
- Visual Regression: Chromatic/BackstopJS with theme permutations.
- Unit Tests: Vitest snapshot CSS vars per brand.
test('BrandA primary color', () => {
switchTheme('BrandA');
expect(getComputedStyle(document.documentElement).getPropertyValue('--color-primary')).toBe('#007BFF');
});
- Adding Brands:
cp tokens/BrandA tokens/BrandC && edit tokens.json && npm run tokens:build.
- Performance: CSS vars are ~1KB gzipped; purge unused via PurgeCSS.
- Accessibility: Tokens include
color-contrast category; validate WCAG at build.
Rollout Phases
- Prototype: Single brand, validate pipeline (1 day).
- Multi-Brand: Add 2nd brand, runtime switch (2 days).
- Guardrails: TS integration + CI (1 day).
- Production: A/B testing integration, monitoring.
This system is zero-runtime-cost (pure CSS), type-safe, and extensible. Total setup: ~1 week for a mid-sized team. Questions on specifics (e.g., Tailwind integration)?