unplugin-style-dictionary
[![npm version][npm-version-shield]][npm]
[![npm downloads][npm-downloads-shield]][npm]
![License][license-shield] [![Build][build-shield]][build-workflow]
[![Test][test-shield]][test-workflow] [![Coverage][coverage-shield]][codecov]
A lightweight, robust unplugin-based plugin to
compile Style Dictionary design tokens ahead of your bundler, with automatic
watching, rebuilding, and hot reloading (HMR) under Vite's dev server.
Built on unplugin, the same core plugin targets Vite, Rolldown,
Rollup, Rspack, and Webpack from a single implementation — useful
when a project has more than one build surface (e.g. Storybook/Vitest on Vite,
and a package build on Rolldown/tsdown) that both need tokens compiled ahead of
them.
Features
- Multi-bundler: One implementation, five entry points — Vite, Rolldown,
Rollup, Rspack, and Webpack.
- Asynchronous builds: Native support for Style Dictionary v5's async
compilation API. The
style-dictionary range in
package.json's peerDependencies is the contract — this
bullet follows it rather than standing beside it.
- Automatic watching: Reads the
source and include patterns from your
Style Dictionary configurations and watches the files they match, including a
token package resolved through node_modules in a workspace. What a change
then triggers depends on the target — see
Watching, per target.
- Config flexibility: Supports file paths (JSON, JSON5, JSONC, JS, MJS, TS),
configuration objects, or functions — including registering custom formats at
config-resolution time.
- Error overlay: A rebuild that fails under Vite's dev server is pushed to
the error overlay rather than only to the terminal, and cleared on the next
one that succeeds.
- Atomic writes: Every generated file is written to a temporary sibling and
renamed into place, and so is every asset the
copy_assets and
android/copyImages actions copy, so code reading one while it is being
rebuilt never sees it half-written. A file whose contents have not changed is
left alone. A custom action gets the same through vol.promises.writeFile,
vol.writeFileSync, vol.promises.copyFile, vol.copyFileSync and
vol.promises.cp; anything else it writes with, such as appendFile or a
write stream, writes in place. A destination that is a symbolic link is
written through to the file it points at, and a replaced file keeps its mode.
A hard-linked destination is replaced rather than updated, so the other link
keeps the old contents.
- Multi-configuration: Can run multiple Style Dictionary configurations in
one build (useful for multi-brand or multi-theme projects). They are compiled
one after another on purpose, so two configurations may safely write to the
same destination; the platforms inside a single configuration are built
concurrently by Style Dictionary itself.
- TypeScript Support: Fully written in TypeScript and exports complete type
definitions.
Installation
npm install @kanso-labs/unplugin-style-dictionary style-dictionary --save-dev
Note: style-dictionary and your bundler (vite, rolldown, rollup,
@rspack/core, or webpack) are peer dependencies, so you can manage their
versions independently.
style-dictionary is the one peer that is not optional, and its range is
^5.0.0. An older major is refused at the install rather than failing later:
npm error code ERESOLVE
npm error Found: style-dictionary@4.4.0
npm error Could not resolve dependency:
npm error peer style-dictionary@"^5.0.0" from @kanso-labs/unplugin-style-dictionary@0.9.0
This package needs Node 22.12 or newer. The floor is where two ranges meet,
neither of them this plugin's own: unplugin, a runtime dependency, declares
engines.node ^20.19.0 || >=22.12.0, and every Style Dictionary 5.x release,
a required peer rather than an optional one, declares >=22.0.0. Only 22.12 and
newer satisfies both, so an older Node cannot install a working set at all. Node
20 reached end of life on 30 April 2026.
Usage
Import the entry point that matches your bundler.
Vite
import StyleDictionary from '@kanso-labs/unplugin-style-dictionary/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
StyleDictionary({
// Path to your Style Dictionary config file
config: 'tokens/config/sd.config.json',
}),
],
})
Keep the generated files out of Vite's build.outDir, which is dist unless
you change it. When that directory sits inside the project root, vite build
empties it once this plugin has compiled, and again on every
vite build --watch rebuild, so tokens written there are gone by the time the
build finishes. Write them somewhere else, such as build/, or set
build.emptyOutDir to false.
Rolldown
import StyleDictionary from '@kanso-labs/unplugin-style-dictionary/rolldown'
export default {
plugins: [
StyleDictionary({
config: 'tokens/config/sd.config.json',
}),
],
}
Rolldown (and tools built on it, like tsdown) is
typically run as a one-shot build rather than a long-lived dev server. There the
plugin compiles tokens once in buildStart, which is enough to guarantee
generated token files exist before the rest of the build consumes them.
Under a real rolldown.watch(), a token edit rebuilds, as it does under the
other targets' watch modes — see Watching, per target.
Rollup / Webpack / Rspack
import StyleDictionary from '@kanso-labs/unplugin-style-dictionary/rollup'
// or: import StyleDictionary from '@kanso-labs/unplugin-style-dictionary/webpack'
// or: import StyleDictionary from '@kanso-labs/unplugin-style-dictionary/rspack'
A webpack.config.js is often CommonJS rather than ESM. This package ships ESM
only, and Node serves a require of it through require(esm), which hands back
the module namespace — so reach for .default:
const {
default: StyleDictionary,
} = require('@kanso-labs/unplugin-style-dictionary/webpack')
module.exports = {
plugins: [StyleDictionary({ config: 'sd.config.json' })],
}
Rspack is webpack's plugin API, and this package treats it as one. Swap the
import for …/rspack and an rspack.config.js reads the same, .default hop
included. Everything below that mentions webpack — where a relative config is
resolved from, where a failed compile is reported, what a config function is
told about the build — holds there too, and tests/webpack-api.test.ts runs the
same cases against both. It installs as @rspack/core, which is the peer this
package declares.
Note: that path needs Node 20.19+ or 22.12+, the versions that can require an
ES module. Every Node release still in support clears it. Importing from ESM has
no such floor.
The subpaths also need a TypeScript moduleResolution of bundler, node16
or nodenext. The deprecated node10 cannot resolve them, and TypeScript 6
already warns that it stops working in 7.
Finding a Config File
With no config, the root is searched for sd.config.json, config.json,
sd.config.js and sd.config.mjs, in that order — and the first one that
looks like a Style Dictionary configuration wins. That means declaring at
least one of platforms, source, include or tokens. A candidate that
fails the check is skipped rather than adopted, so an unrelated config.json —
an extremely common name for something else — no longer gets compiled over and
added to the watch set. The path that was picked is printed, along with any file
skipped on the way, so which configuration a build used is answerable from the
console. When nothing is adopted, the skipped files are reported as an error.
A configuration problem — nothing found, or a named config file that is
missing or will not parse — is said once rather than on every rebuild, and again
only if it comes back after a build that worked.
config.json stays in the list because Style Dictionary's own CLI defaults to
it, so a project relying on that default keeps working.
Two of the four names are modules, and reading a module runs it. A root
sd.config.js is imported when it is first read, and again whenever it changes,
and validation cannot prevent that, because the check can only look at what the
import returned. If you name your configuration explicitly, or have none, say
so:
StyleDictionary({ config: false })
That turns discovery off entirely: nothing is looked for, nothing is watched,
and nothing is compiled. A configuration you name yourself is never
second-guessed by the check above — it goes straight to Style Dictionary.
Config File Formats
A config path may be .json, .json5, .jsonc, .js, .mjs or .ts. The
JSON family is parsed as JSON5, so comments and trailing commas are accepted in
a .json file too — that is what Style Dictionary itself does, and the plugin
reads the file the same way so the watch list and the build never disagree about
what the configuration says.
Two limits worth knowing before you pick one:
- A
.ts config needs Node >= 22.18, where type stripping is on by default.
Below that the build fails with Could not import TypeScript file. That is
higher than the package's own floor of 22.12, so it is a requirement of this
one config format rather than of the plugin — and nothing warns at install
time, because the package installs happily on 22.12.
.cjs is not supported. Style Dictionary has no branch for that extension
and parses it as JSON5, which fails on the first module. Rename the file to
.js in a CommonJS package, or pass a configuration object.
Multiple Configurations
If you have multiple themes or sub-brands, pass an array of config paths or
objects:
StyleDictionary({
config: [
'tokens/config/sd-base.config.json',
'tokens/config/sd-theme.config.json',
],
})
Config Objects
You can pass Style Dictionary configuration objects directly:
StyleDictionary({
config: {
source: ['tokens/**/*.json'],
platforms: {
css: {
transformGroup: 'css',
buildPath: 'build/css/',
files: [{ destination: 'variables.css', format: 'css/variables' }],
},
},
},
})
Custom Formats
config also accepts a function, which is the pattern to use when you need to
register a custom Style Dictionary format (via
StyleDictionary.registerFormat(), or any other register* call) before it's
referenced by name in the returned config. The function re-runs on every build —
including watch-triggered rebuilds under Vite — so the format is always
registered before it's needed; re-registering the same format name on every
rebuild is safe (Style Dictionary silently replaces the existing one).
It runs for builds and for nothing else. A file change that matches no token
source and no config file does not reach it, so a dev server editing unrelated
project files leaves it alone — treat it as the place to prepare a build, not as
a general file-change hook.
It is handed what the host is doing, so the configuration it returns can
depend on it — build an expensive platform on vite build and skip it while the
dev server runs:
styleDictionaryPlugin({
config: ({ command, mode, watch }) => ({
source: ['tokens/**/*.json'],
platforms: {
css: {
transformGroup: 'css',
buildPath: 'build/',
files: [{ destination: 'vars.css', format: 'css/variables' }],
},
// Shells out to a native toolchain, so it is worth a minute of a real
// build and not worth a second of every rebuild.
...(command === 'build' && !watch ? { ios: iosPlatform(mode) } : {}),
},
}),
})
command is 'serve' only under Vite's dev server; every other target builds.
mode is Vite's or webpack's own, and follows command on rollup and rolldown,
which have no such concept. watch is read from the host rather than inferred
from command, because rollup --watch both watches and builds. The full
contract is StyleDictionaryConfigContext.
A function taking no arguments stays valid — TypeScript accepts one of fewer
parameters and JavaScript ignores the extra argument — so the example below
needs no change.
// Named `styleDictionaryPlugin` here to avoid colliding with the `StyleDictionary`
// class imported from the `style-dictionary` package itself, below.
import styleDictionaryPlugin from '@kanso-labs/unplugin-style-dictionary/vite'
import StyleDictionary from 'style-dictionary'
export default defineConfig({
plugins: [
styleDictionaryPlugin({
config: () => {
StyleDictionary.registerFormat({
name: 'custom/my-format',
format: ({ dictionary }) =>
dictionary.allTokens
.map((token) => `${token.name}: ${token.value}`)
.join('\n'),
})
return {
source: ['tokens/**/*.json'],
platforms: {
custom: {
transformGroup: 'css',
buildPath: 'build/',
files: [
{ destination: 'tokens.txt', format: 'custom/my-format' },
],
},
},
}
},
}),
],
})
Platforms
Linux, macOS and Windows. All three run the suite in CI, and Windows is a
Test on Windows job rather than a claim — it was added after two defects
reached main because nothing ran there.
Both are fixed. The atomic write used to fail under the condition it exists for:
with a reader holding the destination open, Windows refuses the rename, so the
compile failed rather than the read being protected. The rename now backs off on
EPERM and EBUSY and retries, bounded, so a rename that genuinely cannot
succeed still fails rather than hanging a dev server.
And a token package resolved through node_modules used to build once and never
rebuild. Vite's watcher cannot be made to deliver those events on Windows — no
spelling of the ignore-list negation reaches them, and watcher.add() does not
either — so the plugin watches those directories itself, on every platform.
Watching, per target
Every target compiles tokens before the build that consumes them. What a later
change to a token file triggers is not the same everywhere, because it depends
on what the host bundler does with the watch list the plugin registers.
| Target |
Compiles before the build |
Rebuilds on a token change |
Safe from rebuild loops |
| Vite |
yes |
yes, under the dev server |
yes |
Vite, build --watch |
yes |
yes, on 6, 7 and 8 |
yes |
| Rollup |
yes |
yes, under rollup --watch |
yes |
| Webpack |
yes |
yes, under webpack --watch |
yes |
| Rspack |
yes |
yes, under rspack --watch |
yes |
| Rolldown |
yes |
yes, under rolldown.watch() |
yes |
Patterns and literal paths behave the same way wherever rebuilds happen at all.
A source of tokens/**/*.json matches a file sitting directly in tokens/ as
well as one in a subdirectory, and a file created after the watcher started is
picked up too.