Sub topic 13
Keeping tokens as source data and generating CSS
This chapter assumes you know how primitive, semantic and component tokens are layered, and how a scope such as [data-theme="dark"] overrides semantic tokens. You also need basic Node.js to run the example.
Why move tokens out of CSS
So far the tokens have lived in a stylesheet. That works for one site. It gets awkward when the same values must also reach an iOS app, an email template, or a design tool such as Figma. Each copy can drift from the others.
The fix is to store tokens once, as plain data, and generate every output from that source. CSS becomes a build artifact, like compiled JavaScript. You edit the data and never edit the generated file by hand.
A source format
A token file is a nested object. Each leaf has a $value, following the shape used by the W3C Design Tokens format. A value like {color.gray-900} is a reference to another token. References are how the source expresses the semantic tier.
{
"color": {
"blue-500": { "$value": "#2563eb" },
"gray-50": { "$value": "#f9fafb" },
"gray-900": { "$value": "#111827" },
"text": { "$value": "{color.gray-900}" },
"surface": { "$value": "{color.gray-50}" },
"accent": { "$value": "{color.blue-500}" }
}
}Save that as tokens.json. The dark theme is a second file that lists only the semantic tokens that change. Save it as tokens.dark.json.
{
"color": {
"text": { "$value": "{color.gray-50}" },
"surface": { "$value": "{color.gray-900}" }
}
}The build script
The script flattens each object into name and value pairs. It joins the path with hyphens, so color plus blue-500 becomes --color-blue-500. It turns each reference into a var() call, so the output keeps the primitive-to-semantic link and a runtime override still works.
import { readFileSync, writeFileSync } from "node:fs";
const read = (file) => JSON.parse(readFileSync(file, "utf8"));
function flatten(node, path = []) {
if ("$value" in node) return [{ name: path.join("-"), value: node.$value }];
return Object.entries(node).flatMap(([key, child]) =>
flatten(child, [...path, key])
);
}
const base = flatten(read("tokens.json"));
const known = new Set(base.map((t) => t.name));
function toCss(tokens, selector) {
const lines = tokens.map(({ name, value }) => {
const resolved = value.replace(/\{([^}]+)\}/g, (_, ref) => {
const refName = ref.split(".").join("-");
if (!known.has(refName)) {
throw new Error(`${name} references missing token ${ref}`);
}
return `var(--${refName})`;
});
return ` --${name}: ${resolved};`;
});
return `${selector} {\n${lines.join("\n")}\n}\n`;
}
const css =
toCss(base, ":root") +
"\n" +
toCss(flatten(read("tokens.dark.json")), '[data-theme="dark"]');
writeFileSync("tokens.css", css);Save it as build-tokens.mjs and run node build-tokens.mjs. It writes this tokens.css:
:root {
--color-blue-500: #2563eb;
--color-gray-50: #f9fafb;
--color-gray-900: #111827;
--color-text: var(--color-gray-900);
--color-surface: var(--color-gray-50);
--color-accent: var(--color-blue-500);
}
[data-theme="dark"] {
--color-text: var(--color-gray-50);
--color-surface: var(--color-gray-900);
}What the pipeline buys you
- One source of truth. A new output format means a new function, not a new copy of the values.
- Build-time validation. A reference to a token that does not exist fails the build. In plain CSS the same mistake only surfaces at runtime as an invalid-at-computed-value-time value.
- Reviewable changes. A diff of
tokens.jsonshows design decisions without generated noise. - Enforced naming. Names come from the path, so the naming convention cannot drift.
Trade-offs
A build step adds a tool to maintain, and it is overkill for a single stylesheet with twenty tokens. Consider it when tokens are shared across platforms or repositories, when several people edit them, or when you want validation. Established tools such as Style Dictionary do the same job with more output formats. A small script like this one is enough until you need them.
Exercise
The dark file contains a typo: {color.gray-5} instead of {color.gray-50}. What happens with the script above, and why is that better than writing the same typo directly in CSS?
Show answer
The build fails with "color-text references missing token color.gray-5", because the name is not in the known set. Written directly in CSS, var(--color-gray-5) would build without error. At runtime the declaration would be invalid at computed-value time, and the property would fall back to its inherited or initial value, which is much harder to trace.