Sub topic 13
Keeping tokens as source data and generating CSS
This chapter assumes you can write custom properties and var() references and that you know the primitive, semantic and component tiers. It also assumes the light and dark theme setup from the earlier chapters and basic Node.js use. Everything here is about where token definitions live, not about new CSS features.
Why move tokens out of CSS
A hand-written :root block works well for one site. It starts to hurt when the same decisions must appear in other places: an iOS app, a Figma file, a JavaScript chart library, an email template. Each copy drifts from the others.
The fix is to treat tokens as data. You keep one file in a neutral format, such as JSON, as the source of truth. A small build step turns it into every format you need. CSS is one output among several.
Keeping tokens as data gives you several things:
- One edit changes every platform.
- A script can validate the data. It can catch unknown references, circular references and missing dark values before the browser does.
- Non-CSS tools such as design tools and documentation generators can read the same file.
- Generated CSS is consistent. Names, ordering and formatting come from code, not from habit.
The cost is a build step and a file you must not edit by hand. For a small single-site project that cost may not be worth paying. Table 1 gives rough decision criteria.
| Situation | Hand-written CSS | Generated from data |
|---|---|---|
| One website, one or two developers | Usually enough | Optional |
| Web plus native apps sharing a palette | Drifts quickly | Strongly preferred |
| Designers edit token values in a design tool | Manual copying | Import or export into the data file |
| Several themes or brands | Many duplicated blocks | One data set per theme |
A source format
A common choice is JSON in the shape the Design Tokens Community Group (DTCG) describes. Each token is an object with a $value, and groups nest to form the name. References to other tokens are written as {path.to.token}.
This file keeps the three layers apart. base holds primitives, light holds the semantic tokens for the default theme, and dark holds only the semantic tokens that change.
{
"base": {
"color": {
"white": { "$value": "#ffffff" },
"gray": {
"200": { "$value": "#e5e7eb" },
"900": { "$value": "#111827" }
},
"slate": { "950": { "$value": "#0b1020" } },
"blue": { "500": { "$value": "#2563eb" } }
},
"space": {
"base": { "$value": "0.25rem" },
"2": { "$value": "calc({space.base} * 2)" },
"4": { "$value": "calc({space.base} * 4)" }
}
},
"light": {
"color": {
"bg": { "$value": "{color.white}" },
"text": { "$value": "{color.gray.900}" },
"accent": { "$value": "{color.blue.500}" }
}
},
"dark": {
"color": {
"bg": { "$value": "{color.slate.950}" },
"text": { "$value": "{color.gray.200}" }
}
}
}The path of a token becomes its CSS name. color.gray.900 becomes --color-gray-900, so the naming convention is enforced by the structure of the file.
The build script
Save the JSON as tokens.json and the script below as build-tokens.mjs. It runs on Node.js 18 or later with no dependencies.
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
const source = JSON.parse(readFileSync("tokens.json", "utf8"));
const REF = /\{([a-z0-9.-]+)\}/g;
const toName = (ref) => ref.replaceAll(".", "-");
const refs = (value) => [...value.matchAll(REF)].map((m) => toName(m[1]));
// Walk the tree and collect { name, value } pairs.
function flatten(node, path = []) {
const out = [];
for (const [key, child] of Object.entries(node)) {
if (key.startsWith("$")) continue;
if (child === null || typeof child !== "object") {
throw new Error(`Invalid token at ${[...path, key].join(".")}`);
}
if ("$value" in child) {
out.push({ name: [...path, key].join("-"), value: String(child.$value) });
} else {
out.push(...flatten(child, [...path, key]));
}
}
return out;
}
const base = flatten(source.base);
const light = flatten(source.light);
const dark = flatten(source.dark);
// 1. Every reference must point at a token that exists.
const known = new Set([...base, ...light].map((t) => t.name));
for (const t of [...base, ...light, ...dark]) {
for (const ref of refs(t.value)) {
if (!known.has(ref)) throw new Error(`--${t.name} references unknown token ${ref}`);
}
}
// 2. Dark may only override semantic tokens that light defines.
const lightNames = new Set(light.map((t) => t.name));
for (const t of dark) {
if (!lightNames.has(t.name)) throw new Error(`dark defines --${t.name}, which light does not`);
}
// 3. No token may depend on itself, directly or through others.
function assertNoCycles(tokens) {
const byName = new Map(tokens.map((t) => [t.name, t.value]));
const visit = (name, trail) => {
if (trail.includes(name)) {
throw new Error(`Circular reference: ${[...trail, name].join(" -> ")}`);
}
for (const ref of refs(byName.get(name))) visit(ref, [...trail, name]);
};
for (const name of byName.keys()) visit(name, []);
}
assertNoCycles([...base, ...light]);
assertNoCycles([...base, ...light, ...dark]); // later entries override earlier ones
// Emit references as var() so the cascade still works in the browser.
function block(selector, tokens, indent = "") {
const lines = tokens.map((t) => {
const value = t.value.replace(REF, (_, ref) => `var(--${toName(ref)})`);
return `${indent} --${t.name}: ${value};`;
});
return `${indent}${selector} {\n${lines.join("\n")}\n${indent}}\n`;
}
const css = [
"/* Generated by build-tokens.mjs. Do not edit. */",
block(":root", [...base, ...light]),
`@media (prefers-color-scheme: dark) {\n${block(':root:not([data-theme="light"])', dark, " ")}}\n`,
block('[data-theme="dark"]', dark),
].join("\n");
mkdirSync("dist", { recursive: true });
writeFileSync("dist/tokens.css", css);
console.log(`Wrote dist/tokens.css (${base.length + light.length + dark.length} declarations)`);Run node build-tokens.mjs. The script prints Wrote dist/tokens.css (13 declarations) and produces this file:
/* Generated by build-tokens.mjs. Do not edit. */
:root {
--color-white: #ffffff;
--color-gray-200: #e5e7eb;
--color-gray-900: #111827;
--color-slate-950: #0b1020;
--color-blue-500: #2563eb;
--space-2: calc(var(--space-base) * 2);
--space-4: calc(var(--space-base) * 4);
--space-base: 0.25rem;
--color-bg: var(--color-white);
--color-text: var(--color-gray-900);
--color-accent: var(--color-blue-500);
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--color-bg: var(--color-slate-950);
--color-text: var(--color-gray-200);
}
}
[data-theme="dark"] {
--color-bg: var(--color-slate-950);
--color-text: var(--color-gray-200);
}The --space tokens appear before --space-base because JavaScript lists integer-like object keys first. Order does not matter for custom properties, since each one is resolved by name at computed-value time.
The generator also removes the duplication you wrote by hand in the dark mode chapter. The dark values are defined once in tokens.json and emitted twice, so the media query block and the data-theme block cannot disagree.
Design decisions in the generator
Emit `var()` references, not resolved values
The script could have written --color-text: #111827; by looking up the primitive. It does not, and this matters. When the output keeps var(--color-gray-900), a later scoped override of a primitive flows through to every semantic token that uses it. The browser, not the build, performs resolution, and it does so per element, so each scope sees its own values.
Resolving values is the right choice for outputs that have no cascade, such as a JavaScript constants file or a native platform file. There the build must resolve references itself.
Validate in the build, not in the browser
A custom property with a bad reference does not raise an error in CSS. A var() that points to an undefined token makes the declaration invalid at computed-value time, and the property silently falls back to its inherited or initial value. Checking at build time moves that failure to where you will see it. The three checks in the script cover most real mistakes:
- Unknown references, usually caused by a typo or a renamed token.
- Dark overrides for tokens that light does not define, which means the theme has a gap or a typo.
- Circular references, which the browser would treat as invalid for every token in the cycle.
Treat the output as a build artifact
Put the Generated ... Do not edit header at the top of the output. Decide once whether dist/tokens.css is committed or built in CI, and keep that decision. Committing it makes code review show the effect of a token change. Not committing it avoids merge conflicts. Either is fine, but a half-edited generated file is not.
Existing tools and formats
You do not have to write the script yourself. Style Dictionary is a widely used build system for tokens. It reads token files, resolves references, and applies transforms and formats to produce CSS, JavaScript, and native platform files. Its newer versions understand the DTCG $value and $type fields used above. Writing a 60-line script, as here, is reasonable when you only need CSS and a few checks. Reach for a tool when you need many output platforms or custom transforms such as unit conversion.
You can also add a $type field (for example color or dimension) to each token. A generator can use it to choose a format for each platform. It can also feed the typed @property registrations from the earlier chapter, so a color token gets syntax: "<color>" automatically.
Common pitfalls
- Editing the generated file. The next build overwrites the change. Add a header comment, and consider marking the file read-only in your repository settings.
- Too many tiers in the data. If component tokens appear in
tokens.json, every component change needs a data change. Keep shared primitive and semantic tokens in the data, and keep component tokens next to the components unless several platforms really need them. - Names that depend on values. A token named
--color-blue-accentbreaks its name when the accent becomes green. The semantic name--color-accentsurvives the change. - Unquoted numeric values. JSON
4becomes4in CSS, which is not a length. The script converts every value withString(), but units still belong in the data ("1rem", not16). - Skipping validation in CI. A build that only runs locally lets broken data reach the repository. Run
node build-tokens.mjsin your CI pipeline and fail on a non-zero exit code, which the thrown errors produce.
Using the output
Link the generated file before your component styles so the tokens exist when the rules are evaluated, even though custom properties resolve at computed-value time and order is flexible.
<link rel="stylesheet" href="dist/tokens.css">
<link rel="stylesheet" href="components.css">Components keep using only var(--color-bg), var(--color-text) and similar names. They need no change when the data file changes, which is the point of the whole arrangement.
Exercise
The generator writes --color-text: var(--color-gray-900); instead of --color-text: #111827;. Name one concrete benefit of this choice in the browser.
Show answer
The reference is resolved by the browser per element, so overriding a primitive such as --color-gray-900 in a scope (for example a [data-brand] container) also changes --color-text inside that scope. A pre-resolved hex value would ignore the override.
Exercise
You add "surface": { "$value": "{color.gray.100}" } to the light group, but color.gray.100 is not defined in base. What happens when you run the build, and why is that better than finding out in the browser?
Show answer
The build throws --color-surface references unknown token color-gray-100 and exits with an error, so no CSS is written. In the browser the same mistake would make the declaration invalid at computed-value time and the property would silently fall back, with no error message.
Exercise
Why does the script call assertNoCycles a second time with the dark tokens included?
Show answer
Dark overrides replace light values for the same names, so a dark token can create a cycle that does not exist in light. For example, color.text in dark could reference {color.text}. Checking the combined map, where later entries override earlier ones, tests the theme the browser will actually see when dark applies.