Skip to content

jptaranto/postcss-design-tokens

Repository files navigation

postcss-design-tokens

PostCSS plugin that provides a function to retrieve design tokens expressed in JS or JSON, within CSS.

:root {
  --blue: token("colors.blue");
}

.foo {
  color: var(--blue);
}
:root {
  --blue: #000066;
}

.foo {
  color: var(--blue);
}

Tokens can be expressed within a .js or .json file and imported via the plugin options.

Install

npm install --save-dev postcss postcss-design-tokens

Configuration

Import your design tokens and add the plugin to the plugins list in postcss.config.js:

const tokens = require("./design-tokens.js")

module.exports = {
  plugins: {
    "postcss-design-tokens": { tokens },
  },
}

Usage

Use the token() function in your CSS to retrieve the token values. Any of the below arg formats are valid (with quotes or without):

.foo {
  font-size: token(large);
  color: token("blue");
}

Use dot notation for nested values:

.foo {
  font-size: token(fontSizes.large);
  color: token("colors.blue");
}

And, ideally use them inside CSS Custom Properties:

:root {
  --font-size-l: token(fontSizes.large);
  --blue: token("colors.blue");
}

.foo {
  font-size: var(--font-size-l);
  color: var(--blue);
}

And media queries:

@media (min-width: token(breakpoint.desktop)) {
  .foo {
    display: block;
  }
}

Or if you're using @custom-media:

@custom-media --desktop-up (min-width: token(breakpoint.desktop));

@media (--desktop-up) {
  .foo {
    display: block;
  }
}

Options

tokens (required)

A JS object of your design tokens. Tokens can be nested to any level and there's no defined structure you need to adhere to.

Instead of defining these inside your postcss.config.js it makes more sense to define them inside either a .js file:

module.exports = {
  color: {
    blue: "#000066",
    shades: {
      lightBlue: "#0074D9",
    },
  },
  fontSize: {
    l: "1.5rem",
    xl: "2rem",
    small: "1rem",
  },
}

Or a .json file:

{
  "color": {
    "blue": "#000066",
    "shades": {
      "lightBlue": "#0074D9"
    }
  },
  "fontSize": {
    "l": "1.5rem",
    "xl": "2rem",
    "small": "1rem"
  }
}

Then, simply require() in your postcss.config.js:

const tokens = require("./design-tokens.json")

module.exports = {
  plugins: {
    "postcss-design-tokens": { tokens },
  },
}

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •