Using Sugarcube with PostCSS

This guide covers how to use Sugarcube with PostCSS in any project, even without a framework. For a complete introduction to Sugarcube, including initialization and basic usage, see our quick start guide and using Sugarcube documentation.

Basic Setup

  1. Initialize Sugarcube in your project:
pnpm dlx make-sugarcube@latest init
npx make-sugarcube@latest init
yarn make-sugarcube@latest init
bunx --bun make-sugarcube@latest init
  1. Import your generated CSS in your project:
src/styles/main.css
@import './global/variables/tokens.variables.css';

Optional Plugin

For the best development experience, we recommend using our PostCSS plugin. This will automatically regenerate your CSS when you make changes to your design tokens.

pnpm add @sugarcube-org/postcss postcss postcss-cli
npm install @sugarcube-org/postcss postcss postcss-cli
yarn add @sugarcube-org/postcss postcss postcss-cli
bun add @sugarcube-org/postcss postcss postcss-cli

Add the plugin to your PostCSS configuration:

postcss.config.js
module.exports = {
plugins: [
require('@sugarcube-org/postcss')
]
}

Build Tool Integration

Using npm scripts

Add a script to your package.json:

package.json
{
"scripts": {
"build:css": "postcss src/styles/input.css -o dist/styles/output.css",
"watch:css": "postcss src/styles/input.css -o dist/styles/output.css --watch"
}
}

Using webpack

webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
require('@sugarcube-org/postcss')
]
}
}
}
]
}
]
}
};

Using Your Tokens

Now you can use your token-generated CSS variables in your project:

body {
background-color: var(--surface-primary);
color: var(--text-primary);
}

Try changing a value in your token files - with the plugin installed, you’ll see the changes instantly in your browser!

Plugin Options

The PostCSS plugin supports the following options:

require('@sugarcube-org/postcss')({
// Whether to suppress success messages
silent: false,
// Whether to only validate tokens without generating CSS
validateOnly: false,
// Whether to check if files are in sync
checkSync: false
})