Skip to content

Style Dictionary & W3C tokens

Use TypeStyles alongside the W3C Design Tokens Community Group (DTCG) format and Style Dictionary for a design-tool-to-code pipeline

TypeStyles already stores your design tokens as real CSS custom properties from TypeScript. The W3C Design Tokens Community Group (DTCG) format and Style Dictionary solve a different problem: exchange. They let designers, documentation sites, iOS / Android apps, and your TypeStyles app all agree on one canonical token set.

This guide shows how to combine them without losing the parts that make TypeStyles pleasant: typed access, scoped variables, and no required compiler.

Who does what

  • W3C DTCG — A JSON file format. Each token is an object with $value, $type, optional $description, and $extensions. Groups nest tokens; aliases reference other tokens with "{color.brand.500}". This is the interchange layer consumed by Figma plugins, Tokens Studio, documentation tools, etc.
  • Style Dictionary — A build-time transformer. It reads DTCG (or its own legacy format), resolves aliases, and emits CSS, SCSS, JS/TS, iOS, Android, and custom formats. It does not run at runtime.
  • TypeStyles — The runtime that turns TypeScript objects into var(--…) custom properties, typed style APIs, themes, and SSR output. It can also read and write DTCG at runtime through typestyles/dtcg, or consume plain TS values generated by Style Dictionary.

The natural split: DTCG is your source of truth, Style Dictionary generates a TypeScript module, and TypeStyles consumes that module through tokens.create(…).

Figma / Tokens Studio → tokens.json (DTCG) → Style Dictionary → tokens/generated.ts → tokens.create(...)
                                                                                         │
                                                                                         ▼
                                                                             real CSS custom properties

A minimal DTCG file

json
// tokens/core.tokens.json
{
  "color": {
    "brand": {
      "500": { "$value": "#3b82f6", "$type": "color" },
      "600": { "$value": "#2563eb", "$type": "color" }
    },
    "text": {
      "default": { "$value": "{color.brand.600}", "$type": "color" }
    }
  },
  "space": {
    "sm": { "$value": "0.5rem", "$type": "dimension" },
    "md": { "$value": "1rem", "$type": "dimension" },
    "lg": { "$value": "1.5rem", "$type": "dimension" }
  }
}

The aliased value {color.brand.600} is resolved by Style Dictionary at build time — by the time your TS module runs, color.text.default is already #2563eb.

Workflow A — DTCG → Style Dictionary → TypeStyles

1. Install and configure

bash
pnpm add -D style-dictionary

Style Dictionary v4 parses the DTCG format natively. Create a config that emits a flat TypeScript primitives module — no CSS output, because TypeStyles owns CSS generation.

js
// sd.config.mjs
import StyleDictionary from 'style-dictionary';

const sd = new StyleDictionary({
  source: ['tokens/**/*.tokens.json'],
  platforms: {
    ts: {
      transformGroup: 'js',
      buildPath: 'src/tokens/generated/',
      files: [{ destination: 'primitives.ts', format: 'typestyles/primitives' }],
    },
  },
});

StyleDictionary.registerFormat({
  name: 'typestyles/primitives',
  format: ({ dictionary }) => {
    const groups = {};
    for (const token of dictionary.allTokens) {
      const [group, ...rest] = token.path;
      const key = rest.join('-'); // e.g. "brand-500"
      (groups[group] ??= {})[key] = token.$value ?? token.value;
    }
    const body = Object.entries(groups)
      .map(([name, vals]) => `export const ${name} = ${JSON.stringify(vals, null, 2)} as const;`)
      .join('\n\n');
    return `// AUTO-GENERATED. Do not edit by hand.\n${body}\n`;
  },
});

await sd.buildAllPlatforms();

Run it whenever tokens change:

bash
node sd.config.mjs

This produces src/tokens/generated/primitives.ts:

ts
// AUTO-GENERATED. Do not edit by hand.
export const color = {
  'brand-500': '#3b82f6',
  'brand-600': '#2563eb',
  'text-default': '#2563eb',
} as const;

export const space = {
  sm: '0.5rem',
  md: '1rem',
  lg: '1.5rem',
} as const;

2. Feed primitives into tokens.create

Keep the DTCG-derived primitives separate from your semantic token layer, so the code stays readable and refactors at the semantic level do not touch design-tool output.

ts
// src/tokens/index.ts
import { createTypeStyles } from 'typestyles';
import { color as corePrimitives, space as corePrimitivesSpace } from './generated/primitives';

export const { style, recipe, tokens } = createTypeStyles({ scopeId: 'app' });

export const color = tokens.create('color', {
  brand: corePrimitives['brand-500'],
  brandHover: corePrimitives['brand-600'],
  text: corePrimitives['text-default'],
});

export const space = tokens.create('space', corePrimitivesSpace);

color.brand is now var(--app-color-brand); the underlying hex came from DTCG.

3. Wire it into your build

Add a prebuild script so the generated file is fresh before type-checking:

json
// package.json
{
  "scripts": {
    "tokens:build": "node sd.config.mjs",
    "dev": "pnpm tokens:build && vite",
    "build": "pnpm tokens:build && vite build"
  }
}

Commit src/tokens/generated/*.ts so tooling (editors, CI, TypeScript) always sees the resolved values.

Workflow B — TypeStyles → DTCG (export to design tools)

Going the other direction — making your TS primitives discoverable to Figma plugins or Tokens Studio — takes a few lines of plain JavaScript. Export the primitive objects (not tokens.create outputs — those are var(...) strings) and walk them into DTCG shape:

ts
// scripts/export-dtcg.ts
import { writeFile } from 'node:fs/promises';
import { primitiveColors } from '../src/tokens/primitives/colors';
import { primitiveSpacing } from '../src/tokens/primitives/spacing';

function toDtcg(values: Record<string, unknown>, $type: string): Record<string, unknown> {
  const out: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(values)) {
    if (value && typeof value === 'object') {
      out[key] = toDtcg(value as Record<string, unknown>, $type);
    } else {
      out[key] = { $value: value, $type };
    }
  }
  return out;
}

const bundle = {
  color: toDtcg(primitiveColors, 'color'),
  space: toDtcg(primitiveSpacing, 'dimension'),
};

await writeFile('dist/tokens.json', JSON.stringify(bundle, null, 2));

This emits a valid DTCG file your design team can import. The primitives are the right export boundary — semantic tokens like color.text are often aliases whose meaning depends on theme and are better expressed as DTCG aliases rather than baked values.

Runtime DTCG with typestyles/dtcg

When you would rather load DTCG JSON directly (for example from a design tool export, an API, or a theme editor), typestyles/dtcg converts between DTCG trees and plain nested objects of values for tokens.create. String and number values come through as they are. Structured values (such as the 2025.10 { colorSpace, components } color form) are not converted: they pass through, and tokens.create flattens them into several custom properties. It has no Style Dictionary dependency and does no file I/O.

ts
import { fromDTCG, toDTCG } from 'typestyles/dtcg';

Reading DTCG with fromDTCG

fromDTCG(tree, options?) flattens a DTCG tree into a nested object of values and resolves {group.token} aliases:

ts
import { createTokens } from 'typestyles';
import { fromDTCG } from 'typestyles/dtcg';
import tree from './tokens/core.tokens.json';

const result = fromDTCG(tree);
if (!result.ok) throw new Error(result.errors.map((e) => `${e.path}: ${e.message}`).join('\n'));

type Nested = { [key: string]: string | Nested };

const tokens = createTokens({ scopeId: 'app' });
// result.value is nested (groups are objects), so type it as a nested record.
const color = tokens.create('color', result.value.color as Nested);

Given the file from earlier, result.value.color is { brand: { 500: '#3b82f6', 600: '#2563eb' }, text: { default: '#2563eb' } }: the {color.brand.600} alias is already resolved. Only whole-value aliases resolve, as in the DTCG spec: "{space.sm}" works, "1px {space.sm}" does not (it is rejected, see below).

fromDTCG never throws. It returns { ok: true, value, warnings } or { ok: false, errors }, where every error is { code, path, message } and code is one of alias-missing, alias-cycle, invalid-token or type-mismatch. Problems are collected in one pass, so you can show them together, up to maxErrors (default 100): past it, the last entry is an invalid-token error with path '' that says how many more there were, and the tree walk stops early. fromDTCG also accepts null or a non-object as options and uses the defaults. Paths in errors are cut to 200 characters. $type is compared between a token and the token its alias points at, not along the whole chain.

warnings is a list of "path: message" strings for things that still load but probably are not what you meant: a structured (object or array) value that passed through, a token that also has child keys (the children are ignored), a dark value on a group's dev.typestyles extension (put it on each token), and a dev.typestyles extension that is not an object. At most maxWarnings (default 100) are returned; past it, a last line says how many more there were.

Untrusted input

fromDTCG is built to read theme JSON you did not write, such as a theme stored in a database. It limits how much work a tree can cause and rejects names and values that could break out of CSS, all as invalid-token:

  • Size limits. Pass maxDepth (default 32), maxNameLength (default 128) and maxTokens (default 50,000) to change them. A name or level past the limit is reported and its subtree is skipped; going past maxTokens stops the walk. maxErrors and maxWarnings (default 100 each) bound the size of the result.
  • Names (every group and token key, and keys inside structured values) may only contain letters (in any script, including combining accents), digits, - and _, and may not be empty. tokens.create joins names into a custom-property name such as --color-brand-500 without escaping, so any other character (/, +, %, #, &, *, spaces, . and so on) would produce a name the browser drops. Names such as 500, 2xl, brand-500, snake_case and Über are fine. Keys named __proto__ are also rejected.
  • String values ($value, dark values, resolveExternal results, and strings inside structured values) may not contain ;, {, }, <, >, \ or control characters, including newlines. They also may not contain a CSS comment delimiter (/* or */), a string that is not closed, or unbalanced brackets, because an open comment, string, ( or [ swallows the rest of the stylesheet. A " or ' starts a string that only the same quote ends (so "Children's Font" is fine), and every ( and [ outside a string must be closed in order, nested at most 32 deep (calc(1px + (2px * 3)) is fine; calc(1px, a) and (] are not). url( is rejected anywhere in a value, in any case and even inside quotes: theme tokens are colors, fonts, sizes and shadows, DTCG has no url type, CSS reads url( by special rules that are easy to get wrong, and url() would make the browser send requests. Commas, #, %, * and / are fine, so font stacks such as "Inter", sans-serif, shadows, calc(100% / 3) and var(--x) keep working. An alias is checked after it resolves. null and undefined values are rejected; numbers and booleans are fine.

Trust boundary. These checks stop a value from closing a declaration, rule or <style> element, but fromDTCG is not a general sanitizer. Do not pass untrusted data to anything that puts CSS into HTML without escaping it.

Light and dark values

DTCG has no built-in modes, so typestyles stores the dark value under the dev.typestyles key in $extensions. The token's $value is the light (default) value:

json
{
  "color": {
    "$type": "color",
    "surface": {
      "$value": "#ffffff",
      "$extensions": { "dev.typestyles": { "dark": "#111827" } }
    }
  }
}

fromDTCG turns that token into { light: '#ffffff', dark: '#111827' }, the { light, dark } leaf shape that color-mode tokens use (register color modes first; see Tokens). Aliases resolve per mode: a dark value that aliases {color.brand.600} picks up that token's dark value if it has one. A token without modes that aliases a mode-aware token becomes { light, dark } as well, so it follows the target.

Aliases to tokens outside the tree

If an alias points at a token that is not in the tree, fromDTCG returns an alias-missing error. Pass resolveExternal to supply the value yourself as a string (return undefined, or anything that is not a string, to leave it unresolved). The string is checked like any other value:

ts
const result = fromDTCG(tree, {
  resolveExternal: (path) => (path === 'core.white' ? '#ffffff' : undefined),
});

Writing DTCG with toDTCG

toDTCG(tokens, options?) goes the other way. Pass the primitive values (not tokens.create output, which is var(...) strings). { light, dark } leaves become a $value plus the dev.typestyles extension. Use typeOf to attach a $type by dotted path:

ts
const doc = toDTCG(
  { color: { brand: '#3b82f6', surface: { light: '#ffffff', dark: '#111827' } } },
  { typeOf: (path) => (path.startsWith('color.') ? 'color' : undefined) },
);

await writeFile('dist/tokens.json', JSON.stringify(doc, null, 2));

toDTCG is best-effort and never throws. It silently skips undefined, null, functions, symbols, bigints, keys that start with $, __proto__ keys and entries that throw when read, and it drops anything nested more than 64 levels deep without telling you. An object that contains itself (directly or through its children) is written once; the reference back is skipped. An object used in several places is written at each place, up to maxNodes groups and tokens in total (default 50,000): past it, toDTCG stops and returns what it converted so far. Values are written as plain strings such as "#3b82f6" and "16px"; object-form values (for example the structured color and dimension values in the 2025.10 format module) pass through untouched.

Names are written as they are, so a key such as a.b or x{ produces a document that is not valid DTCG (and that fromDTCG rejects). A literal string value that looks like an alias, such as "{b}", is written as is and becomes an alias when you read the document back.

Themes and color modes across the boundary

DTCG does not yet standardise multi-mode tokens. Two pragmatic patterns work well with TypeStyles. (To read modes at runtime instead, see Light and dark values above.)

Pattern 1 — one file per mode

tokens/
  core.tokens.json          # mode-agnostic (spacing, radii, typography)
  color.light.tokens.json   # color/* in light mode
  color.dark.tokens.json    # color/* in dark mode

Run Style Dictionary twice (one platform per mode) into separate primitive modules, then feed each into a tokens.createTheme:

ts
import { color as lightColor } from './generated/light';
import { color as darkColor } from './generated/dark';

export const darkTheme = tokens.createTheme({
  name: 'dark',
  tokens: { color: { brand: darkColor['brand-500'], text: darkColor['text-default'] } },
});

Pattern 2 — DTCG $extensions for modes

Tokens Studio and many design tools carry mode variants under $extensions. Read them in a custom Style Dictionary format and emit one primitive module per mode. From TypeStyles' perspective it looks exactly like Pattern 1 — tokens.createTheme plus tokens.colorMode.* presets (see Tokens and Theming patterns).

Aliases: build-time vs runtime

You have two valid strategies for DTCG aliases like {color.brand.500}:

  • Resolve at build time — the default Style Dictionary behavior. color.text.default lands in your TS module as a literal hex. Pro: simple, zero runtime cost. Con: the link between semantic and primitive is lost in code.
  • Preserve as var(...) at runtime — emit the primitives with tokens.create, then reference them from a second tokens.create call. Aliases resolve via the CSS cascade. Pro: themes can swap primitives without rebuilding. Con: requires two token namespaces.
ts
const primitive = tokens.create('primitive-color', { brand500: '#3b82f6' });
const semantic = tokens.create('color', {
  brand: primitive.brand500, // var(--app-primitive-color-brand500)
});

The second strategy is worth the extra layer when you ship multiple brand themes that share the same semantic contract.

Matching external CSS names

When Style Dictionary (or another tool) already defines your canonical --* naming convention, mirror it with nameTemplate on tokens.create so TypeStyles refs point at the same names TypeStyles injects — without duplicating :root blocks from SD.

ts
const tokens = createTokens({ scopeId: 'acme' });

// SD might emit --color-brand-500; match that pattern (drop scope from var names if globals are unscoped).
const color = tokens.create('color', generatedPalette, {
  nameTemplate: ({ segments }) => `--color-${segments.join('-')}`,
});

const semantic = tokens.create(
  'color-semantic',
  {
    text: { primary: color.brand[500] },
  },
  {
    nameTemplate: ({ path }) => `--ds-color-${path}`,
  },
);

Defaults are still recommended for new apps — custom names are for interop and migration, not aesthetics. scopeId on createTokens / createStyles still scopes theme classes even when var names match globals.

Gotchas

  • Do not let Style Dictionary emit the CSS. If both Style Dictionary and TypeStyles ship :root { --color-brand: … }, you get duplicate declarations and scoping conflicts. Keep TypeStyles as the single source of CSS.
  • Do not pass tokens.create output to DTCG exporters. It contains var(--…) strings, not literal values. Export the underlying primitive objects instead.
  • Type your generated module. Keep as const in the Style Dictionary format so TypeStyles' inference preserves literal key types. Missing keys become type errors at the tokens.create call site.
  • Version the JSON, generate the TS. Treat tokens/*.tokens.json as the reviewed artefact and src/tokens/generated/** as derived output. Some teams commit both; some gitignore the generated TS and rebuild in CI. Either works — pick one and stick with it.
  • Scope still matters. Style Dictionary does not know about TypeStyles' scopeId. When you change scopeId, only the TypeStyles side updates — the DTCG file is unchanged because it describes design intent, not emission naming.
  • Tokens — the tokens.create, createTokens, and createTheme APIs.
  • Design system — three-layer token architecture (primitives / semantic / component) that this pipeline slots into.
  • Theming patterns — multi-theme and color-mode strategies.
  • Open Props — pre-built primitive tokens, an alternative starting point when you do not have a design-tool source of truth yet.