Easily Use Design Tokens In Eleventy

This is going to be a very short article, because it turns out working with design tokens in Eleventy is a partition of urine (very easy).

Eleventy’s root /_data folder lets you define some global (you guessed it) data that can be accessed in templates anywhere in the site/project. So, if I create a tokens.json file in my _data folder with a colorLight property, I can interpolate it as {{ tokens.colorLight }} in any of my nunjucks templates.

Here’s /_data/tokens.json:

{
  "colorLight": "#eee",
  "colorDark": "#111"
}

Ordinarily you would use nunjucks (other templating engines are available) to render HTML. But Eleventy allows me to set permalinks with any file extension. So getting these values into my CSS just means creating a theme.njk file and telling Eleventy to output it at css/theme.css.

Here’s /css/theme.njk:

---
permalink: "css/theme.css"
---

:root {
  --colorLight: {{ tokens.colorLight }};
  --colorDark: {{ tokens.colorDark }};
}

These custom properties would, of course, be referenced throughout the rest of my CSS.

You may ask, “if you’re using custom properties anyway, why not just define your tokens there?” One reason is that it’s simpler to reuse or generate JSON than CSS. Usually, design tokens are canonically JSON. The more pertinent reason is that the whole point of design tokens is interoperability; they should be usable across different kinds of files. Since I want my site/app to be a PWA (Progressive Web App) I’ll be wanting to share these same tokens to my manifest.json file.

Here’s the (abridged) /manifest.json:

---
permalink: "manifest.json"
---

{
  "theme_color": "{{ tokens.colorDark }}",
  "background_color": "{{ tokens.colorLight }}"
}

Netlify CMS allows one to alter the properties of data files directly, using the file collection type.

Inside Netlify CMS’s config.yml:

- label: "Theme"
  name: "theme"
  file: "/_data/tokens.json"
  fields:
    - { label: "Light color", name: colorLight, widget: string }
    - { label: "Dark color", name: colorDark, widget: string }

So there it is: an extremely simple setup for using design tokens in Eleventy, with content management support on top. And you can’t call these design tokens “spicy Sass variables” because I didn’t use Sass, so there.