Using Sugarcube with 11ty

This guide covers how to use Sugarcube with 11ty projects. 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 11ty template:
_includes/base.njk
<link rel="stylesheet" href="/styles/global/variables/tokens.variables.css">

Optional Plugins

For the best development experience, we recommend using one of our build tool plugins. 11ty supports both Vite and PostCSS approaches.

Using Vite

pnpm add @11ty/eleventy-plugin-vite @sugarcube-org/vite
npm install @11ty/eleventy-plugin-vite @sugarcube-org/vite
yarn add @11ty/eleventy-plugin-vite @sugarcube-org/vite
bun add @11ty/eleventy-plugin-vite @sugarcube-org/vite

First, add the 11ty Vite plugin to your .eleventy.js:

.eleventy.js
import EleventyVitePlugin from "@11ty/eleventy-plugin-vite";
export default function (eleventyConfig) {
eleventyConfig.addPlugin(EleventyVitePlugin);
};

Then add the sugarcube Vite plugin to your vite.config.js:

vite.config.js
import { defineConfig } from 'vite'
import sugarcube from '@sugarcube-org/vite'
export default defineConfig({
plugins: [sugarcube()]
})

Using PostCSS

Alternatively, you can use the PostCSS plugin:

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

Add the plugin to your postcss.config.js:

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

Then in your .eleventy.js configuration, ensure PostCSS is set up:

.eleventy.js
const postcss = require('postcss')
const postcssConfig = require('./postcss.config.js')
module.exports = function(eleventyConfig) {
// Add PostCSS processing
eleventyConfig.addTemplateFormats('css')
eleventyConfig.addExtension('css', {
outputFileExtension: 'css',
compile: async function(inputContent) {
return async function() {
const result = await postcss(postcssConfig.plugins).process(inputContent)
return result.css
}
}
})
}

Using Your Tokens

Now you can use your token-generated CSS variables in your 11ty templates:

<div class="card">
<h2 style="color: var(--text-primary)">Hello World</h2>
<p style="background-color: var(--surface-primary)">This is using Sugarcube tokens!</p>
</div>

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