@kanso-labs/unplugin-style-dictionary
v0.10.75
Published
Compile Style Dictionary design tokens ahead of your bundler (Vite, Rolldown, Rollup, Webpack or Rspack) from a single unplugin-based plugin, rebuilding on a token change under Vite's dev server and each bundler's watch mode
Readme
unplugin-style-dictionary
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-dictionaryrange inpackage.json'speerDependenciesis the contract — this bullet follows it rather than standing beside it. - Automatic watching: Reads the
sourceandincludepatterns from your Style Dictionary configurations and watches the files they match, including a token package resolved throughnode_modulesin 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_assetsandandroid/copyImagesactions 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 throughvol.promises.writeFile,vol.writeFileSync,vol.promises.copyFile,vol.copyFileSyncandvol.promises.cp; anything else it writes with, such asappendFileor 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-devNote: 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: [email protected]
npm error Could not resolve dependency:
npm error peer style-dictionary@"^5.0.0" from @kanso-labs/[email protected]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
.tsconfig needs Node >= 22.18, where type stripping is on by default. Below that the build fails withCould 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. .cjsis not supported. Style Dictionary has no branch for that extension and parses it as JSON5, which fails on the firstmodule. Rename the file to.jsin 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.
Rolldown rebuilds on macOS too, a token reached through a symbolic link
included. Its watcher there drops the events for a path registered through a
link — a workspace package linked into node_modules, or a project under /var
or /tmp, both of which are links on macOS — so the plugin registers each such
path by its realpath as well, and maps the event back to the spelling your
source patterns use. This table used to call rolldown platform-dependent, and
it was the link: the measurement behind that ran in a directory under /var.
The same cases rebuild on Linux and on Windows, where CI runs them.
A token package resolved through node_modules is watched too, and that took
a fix. In a workspace — app/node_modules/@acme/tokens symlinked to
packages/tokens — Vite's dev-server watcher is built with **/node_modules/**
already in its ignore list, and the entries a consumer adds are appended after
it rather than subtracted from it. So the first build was correct and no edit
ever rebuilt, with nothing printed to say so. The plugin now un-ignores exactly
the files it registers, by name, on Vite 6, 7 and 8. The rest of node_modules
stays ignored, which matters: handing the whole dependency tree to the watcher
is thousands of files no token build reads.
vite build --watch had the same problem and gets the same fix on Vite 6 and 7,
which build on rollup's watcher and its chokidar ignore list: the plugin appends
the same negations to build.watch.chokidar.ignored. Vite 8 builds with
rolldown, which takes no ignore list from there and needs none: a linked token
package rebuilds there through the realpath registration the Rolldown note above
describes.
Nothing is needed from you for that. If you had worked around it with a
server.watch.ignored or build.watch.chokidar.ignored negation of your own,
it still works — the plugin appends to your list rather than replacing it.
"Safe from rebuild loops" is worth stating because consuming code imports the
generated file, so every regenerate is itself a change the host reacts to. The
plugin subtracts its own output from the watch list, skips recompiling when a
watch rebuild re-enters buildStart, and skips the write entirely when a
rebuild renders bytes identical to what is already on disk.
Building Only Some Platforms
Every rebuild used to compile every platform, so a dev server serving a web app
paid for Objective-C headers, Android XML and Dart classes on every token save.
platforms narrows it:
StyleDictionary({
config: 'sd.config.json',
// Build everything once, then rebuild only css while serving.
platforms: { watch: ['css'] },
})Measured on a six-platform configuration (css, scss, js, ios, android, flutter), with the timer around the build call alone:
| Tokens | All platforms | css only | Saved | | ------ | ------------- | -------- | ------ | | 500 | 12 ms | 1 ms | 10 ms | | 3,000 | 36 ms | 2 ms | 34 ms | | 10,000 | 103 ms | 4 ms | 99 ms | | 30,000 | 330 ms | 12 ms | 319 ms |
An array — platforms: ['css'] — applies to every build. The object form splits
the first compile from the watch rebuilds, and an omitted key means every
platform. A name the configuration does not define is an error, matching Style
Dictionary's own CLI.
Unselected platforms keep whatever they last wrote. Nothing removes or
refreshes their files, so scoping the build half ships stale output for the
rest. Scope watch unless that is what you want.
Generated Output Is Disposable
Nothing removes a generated file, ever. Drop a files entry from a
configuration, remove a whole platform, or move a buildPath, and the old
output stays where it was — still resolving, still importable, still carrying
its old token values, and in a package build still published, with nothing in
the log mentioning it.
So treat the build directory as disposable: delete it when a configuration changes shape, and keep it out of version control and out of any directory holding hand-written files.
Keep it out of the bundler's own output directory as well, which is the opposite
problem. Vite empties build.outDir when it starts writing its bundle, after
this plugin has compiled, whenever that directory sits inside the project root —
dist, by default — so a buildPath under it leaves nothing behind after
vite build, and nothing after a vite build --watch rebuild either. An
outDir outside the root is not emptied unless build.emptyOutDir asks for it.
Put the buildPath somewhere else, or set build.emptyOutDir to false.
There is deliberately no clean option. Style Dictionary's
cleanAllPlatforms() does not solve this — it removes the destinations the
current configuration declares, which are exactly the files that are not
orphans, and it removes the buildPath directory along with them. Measured:
after dropping legacy.scss from a configuration, a clean run left
legacy.scss standing and deleted vars.css, the file still in use.
Skipping a Build That Would Change Nothing
A configuration whose output already reflects everything it reads is not
compiled again. buildAllPlatforms is around 80% of a build, and under Vite it
runs inside server.listen() — so without this the dev server refused
connections for the length of a compile whether or not a token had changed.
Three things are compared: every file the configuration reads (its source and
include matches, its own config file, and anything named by watch), every
file it declares, and the configuration that last wrote them. That last one
covers more than the configuration's own contents. It includes the hooks the
configuration names — each format, filter, fileHeader, transform,
transform group, parser and preprocessor it refers to by name — as Style
Dictionary's registry holds them, and the Style Dictionary version. So a new
body registered under a name it uses, which is what editing the
Custom Formats pattern does, rebuilds even though no file
moved, and so does an upgrade.
Once a configuration has been compiled, the files it reads are compared against
what that compile saw before it started reading. A token saved while a rebuild
is compiling is newer than that, so the rebuild queued for it runs, even though
the output the rebuild went on to write is newer still. The record of what each
compile read is kept in node_modules/.cache/unplugin-style-dictionary, beside
the nearest package.json, so it survives a restart. Where there is no record,
the files a configuration reads are compared against the files it declares.
A declared file that changed since the compile that wrote it is compiled over
rather than trusted, whatever its mtime says. Each compile records the mtime,
size and inode of every file it wrote, and a file that no longer has all three
is built again: a rewrite of another length moves the size, and a file replaced
by a rename, which is how atomic-save editors and rsync write, moves the
inode, even where the mtime was put back or never moved. Generated output is
disposable, so an edit made to it by hand does not survive the next build.
One rewrite is still not seen: one of the same length, made in place, inside the
timestamp tick the compile wrote in — about 15ms on Windows, and a whole second
or more on HFS+, ext3 and FAT. It moves none of the three, and only reading
every output on every build could catch it, which is the cost the skip exists to
avoid. Set cache: false where something rewrites generated output that
quickly.
Two cases never skip, because neither can be settled from the filesystem:
| Case | Why |
| ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The first compile of a process, for a configuration given as an object or a function | There is no config file to stat, so an edit to the object inside vite.config.ts moves no mtime. Within one process the resolved configuration is compared against the one last built. An earlier process's record is not trusted for it, because its functions are compared by their source and what they close over can differ. |
| A platform declaring actions | An action writes what no destination names, so a skip would leave its work undone. |
A hook's own code is compared, but not what it calls from another module. Name
that module in watch and an edit to it rebuilds on the next start. A custom
format that reads something off-disk — an environment variable, a network call —
cannot be detected this way either. Set cache: false where that is the case,
and every build runs.
One Compile per Process
A bundler instance that asks for a compile while an identical one is already running waits for it rather than starting a second. Generated token files are a side effect on the filesystem, not per-bundler output, so there is nothing to gain from writing them twice.
This is not a rare case. One process often holds several instances of the
plugin: a single vitest run on a project with two test projects and browser
mode stands up five Vite servers — the root one, one per project, and one more
per project once its HTTP server listens — and every one of them runs
buildStart.
Two configurations are treated as the same compile only when they resolve to the same root and the same configuration, functions included, so one script building two packages shares nothing between them. The sharing lasts exactly as long as the compile does: it stops two instances doing the same work at the same time, and does not cache anything for later.
Where Paths Are Resolved From
Two bases, and which one applies depends on whose path it is.
The config option is the plugin's, so a relative path is looked up under
the host's root: Vite's root, webpack's or rspack's context, and the working
directory for rollup and rolldown, which report none. root overrides that.
Everything inside a Style Dictionary configuration is Style Dictionary's, so
source, include and buildPath are resolved against the working directory.
That is what Style Dictionary itself does — combineJSON globs each pattern
with no directory of its own — so a configuration behaves the same here as it
does under the Style Dictionary CLI.
The consequence worth knowing: a configuration kept in a subdirectory names its tokens relative to where the build runs, not relative to itself.
// tokens/config/sd.config.json, with the build run from the project root
{
// read from <project root>/tokens, not from tokens/config/tokens
"source": ["tokens/**/*.json"],
}Absolute paths sidestep the question entirely, and are worth reaching for when the build might be run from more than one directory.
Logging
Style Dictionary says useful things while it builds — a name collision, a
reference it could not resolve, No tokens for vars.css. File not created. —
and the plugin used to suppress all of it by overwriting log.verbosity on the
way past. It no longer touches that setting unless asked, so whatever your
configuration sets now reaches you.
logLevel overrides it from the plugin side:
StyleDictionary({
config: 'sd.config.json',
// 'silent' | 'warn' | 'info' | 'verbose'. Unset leaves your config's own
// log.verbosity alone, which is the default.
logLevel: 'warn',
})'warn' is the level worth knowing about: Style Dictionary's warnings without
the plugin's own progress lines and size table. Style Dictionary's own lines
stay — the platform name and the ✔︎ for each file it wrote — because 'warn'
leaves its verbosity at the default, and only 'silent' quiets them.
silent: true is an alias for 'silent'.
A compile that fails is reported at every level, including 'silent', which is
why there is no 'error'. log.warnings is never touched: if your
configuration turns a warning into a thrown build, that stays your decision.
Where the messages go
Through your bundler, not straight to the console, and each one takes them its own way:
| Target | Progress lines and size table | A failed compile |
| ------------------ | ----------------------------- | ---------------------------------- |
| Vite | config.logger.info | config.logger.error |
| Rollup, Rolldown | the plugin context's log | the context's warning channel |
| Webpack, Rspack | the console | compilation.warnings, so stats |
| No host (one-shot) | the console | the console |
That is what makes a customLogger and clearScreen work under Vite, and what
puts a failed compile into stats.toJson() under webpack — where it reaches CI
annotations and anything else reading the build's own output.
Rspack reformats what it is given, and webpack does not. The plugin hands
both the same plain text; rspack wraps every diagnostic in its own frame — a ⚠
marker and a │ gutter — and colours that frame whenever it thinks colour is
wanted, which setting CI is enough to do. So a warning read out of rspack's
stats can carry ANSI escapes that came from rspack rather than from here.
Strip them before feeding that text to anything that expects plain output.
A failure is reported as a warning, never on the host's error channel.
Rollup's this.error aborts the bundle, so reporting a failure through it would
stop every build that reported one — taking the decision failOnError exists to
make. The same reasoning puts webpack's report in compilation.warnings rather
than compilation.errors, so failOnError: false really does leave the build
passing.
Your bundler's own log level applies. vite --logLevel silent silences
Vite's logger, and the plugin's lines are Vite's logger's now, so they go too —
the size table included. Style Dictionary's own lines are not among them: the
platform name and the ✔︎ for each file it wrote are its own console calls, so
they still print unless the plugin's logLevel is 'silent'. Nothing is lost
by it that matters: failOnError decides whether a broken token set stops the
build, and it decides that whether or not anything was printed.
Colour follows the usual conventions, which it previously ignored entirely: no
escapes when NO_COLOR is set, or when the stream is not a terminal, or under
TERM=dumb; escapes when FORCE_COLOR is set to anything but 0, including on
a non-terminal, which is what that variable is for. NO_COLOR wins over
FORCE_COLOR. stdout and stderr are decided separately, because they are
redirected separately.
Failing the Build
A token compile that fails stops the build. vite build, rollup and webpack
exit non-zero with Style Dictionary's own message, rather than finishing green
and shipping whatever the previous run wrote.
A watch-triggered rebuild only reports the failure, so a dev server survives a
half-typed token file. failOnError moves that line:
StyleDictionary({
config: 'sd.config.json',
// 'build' is the default. 'serve' fails rebuilds instead, true fails both,
// false restores the old report-and-continue behaviour.
failOnError: true,
})A configuration that resolves no tokens is a failure, not an empty build.
Style Dictionary writes the destination with nothing in it and reports success,
so a token file deleted mid-session used to take the generated output down with
it, and a source matching nothing shipped an empty stylesheet from a build
that exited 0. The check runs before the compile, so the previous good output is
still on disk when it fires and nothing is overwritten. The message names the
configuration and the patterns that matched no files.
This is about the resolved token set, not about the patterns: a configuration
that supplies tokens inline and declares no source at all is valid and
builds. And it goes through failOnError like any other compile failure, so
failOnError: false reports it and carries on.
A failure is always reported by the plugin, whatever failOnError and silent
are set to — see Where the messages go for which
channel it arrives on, and for the one thing that can still suppress it.
Under Vite's dev server it is reported to the browser as well. A failed rebuild
is pushed to Vite's error overlay, naming this plugin and carrying Style
Dictionary's message, and the overlay is dismissed by the next rebuild that
succeeds — so a page left rendering the last good token file says so instead of
looking current. Set errorOverlay: false to keep the failure in the terminal
only.
failOnError and errorOverlay answer different questions and do not interact:
the first decides whether the host stops, the second whether the browser is
told. The dev server's default is not to stop, which is exactly when the overlay
is the only thing that can report the failure.
Build Hooks
Three optional callbacks, for work that has to happen around a compile rather than inside one — formatting the generated files, type-checking them, telling something else they have landed.
StyleDictionary({
config: 'sd.config.json',
onBuildStart: () => console.log('compiling tokens'),
onBuildEnd: async (files, durationMs) => {
console.log(`wrote ${files.length} files in ${durationMs}ms`)
await formatGeneratedFiles(files)
},
onBuildError: (error) => notifySomething(error),
})files holds the absolute, platform-native path of every file the build
declares that is on disk, sorted. It is what the build declares rather than what
it happened to write this time: a configuration skipped because its output was
already current contributes its destinations too, so a post-processing step
still sees the whole set on a rebuild that changed one file. A declared file
Style Dictionary declined to write, such as one whose filter matched no tokens,
is left out.
A rebuild is a build, so all three fire again on every watch-triggered one.
A hook cannot fail the build that called it. The return value is not awaited, so nothing waits for post-processing; a hook that throws is reported and the build stands, and a promise that rejects is caught and reported rather than reaching the host as an unhandled rejection — which would otherwise take a dev server down from inside a step meant to reformat a file.
onBuildError fires whatever failOnError is set to, and before that option
decides whether to rethrow. The two answer different questions: one is whether
the host stops, the other is that a build went wrong.
A failure names the configuration it came from. Style Dictionary's own
errors name neither the configuration nor the file behind them, so the plugin
wraps them: the message opens with the configuration's path, or its position in
the list, and Style Dictionary's error is the cause. A failed rebuild also
names the change it followed — the last file to change, which is not necessarily
the one that broke the build.
Public API
Small on purpose. Five bundler entry points, one root entry, and two types.
| Import | What it is |
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| …/vite, …/rolldown, …/rollup, …/rspack, …/webpack | Default export: the plugin for that bundler. Call it with the options below. |
| … (the root) | Default export, also named unplugin: the unplugin instance. Its .vite, .rolldown, .rollup, .rspack and .webpack are the five supported targets, the same plugins the subpaths export. It also carries unplugin's own .esbuild, .farm, .unloader, .rsbuild, .bun and .raw, which are not supported here: .esbuild throws on its first build, and nothing tests the others. |
| UnpluginStyleDictionaryOptions | The options type, exported from every entry above. |
| StyleDictionaryConfigContext | What the function form of config is handed, exported from every entry above. |
Anything not in that table is internal, whatever a build output happens to
contain. In particular the watch filter and the raw unplugin factory are not
exported: the filter answers a question only this plugin asks, and the factory
takes a second meta argument — the bundler-identifying UnpluginContextMeta —
that a consumer would have to construct by hand, so calling it the obvious way
is a type error rather than a plugin.
Reach for the root entry when one configuration object feeds more than one bundler:
import styleDictionary from '@kanso-labs/unplugin-style-dictionary'
const options = { config: 'sd.config.json' }
const forRollup = styleDictionary.rollup(options)
const forWebpack = styleDictionary.webpack(options)It is not a way to reach a bundler that has no subpath. Every target without one
is unplugin's own and unsupported here. esbuild in particular fails outright:
the plugin registers its watch list before it compiles, and unplugin's esbuild
context throws on that registration, so .esbuild writes nothing even for a
one-shot build.
Options Reference
/**
* What the host is doing, handed to the function form of `config` so it can
* decide what to build.
*
* Only Vite reports all three. Where a host does not say, the value is
* derived rather than guessed at, and each field below says how.
*/
export interface StyleDictionaryConfigContext {
/**
* Whether the host is serving or building.
*
* `'serve'` comes from Vite's own `config.command` and is the dev server.
* Every other target builds, so it is `'build'` there — rollup, rolldown and
* webpack have no serving mode of their own to report.
*/
command: 'build' | 'serve'
/**
* The host's mode, as it names it.
*
* Vite reports its `config.mode` — `'development'` serving,
* `'production'` building, or whatever `--mode` named. webpack reports its
* `mode` option. rollup and rolldown have no such concept, so the value
* follows `command`: `'development'` when serving, `'production'` when
* building.
*/
mode: string
/**
* Whether the host will keep rebuilding.
*
* `true` under Vite's dev server and `vite build --watch`, `rollup --watch`,
* `rolldown.watch()` and `webpack --watch`; `false` for a one-shot build. It is read from the
* host — the plugin context's `meta.watchMode` on the three rollup-shaped
* targets, and `compiler.watchMode` on webpack — rather than inferred from
* `command`, because `rollup --watch` both watches and builds.
*/
watch: boolean
}
/**
* Options for the Style Dictionary unplugin factory, shared across all bundler
* targets (Vite, Rolldown, Rollup, Webpack, Rspack).
*
* Every target compiles tokens before the build that consumes them. Live
* rebuild-on-change is driven by the host bundler's watch mode, because token
* source files sit outside the module graph: Vite's dev server, `rollup
* --watch`, `rolldown.watch()`, `webpack --watch` and `rspack --watch` all
* rebuild on a token change, and a one-shot build (e.g. `tsdown`/`rolldown
* build` without `--watch`) only builds once, in `buildStart`.
*
* What the plugin says goes through the host wherever the host has a channel
* for it: Vite's `config.logger`, the plugin context under rollup and
* rolldown, and `compilation.warnings` under webpack and rspack, which is what
* puts a failed compile in `stats.toJson()`. The progress lines and the size
* table take the host's `info` channel, and webpack and rspack have none, so
* there both go to the console. A failure is reported on the warning channel
* and never the error one — rollup's `this.error` aborts the bundle, and that
* decision is `failOnError`'s alone. Where no host offers a channel the console
* is used, with colour gated on `NO_COLOR`, `FORCE_COLOR` and whether the
* stream is a terminal.
*
* Style Dictionary's own lines are not the plugin's. The platform name and the
* `✔︎` for each file it wrote are its own `console` calls, so they reach the
* console under every host, whatever the host's log level. `logLevel: 'silent'`
* quiets them, as does `log.verbosity: 'silent'` in the configuration.
*
* The three `onBuild*` hooks are called synchronously and their return value
* is not awaited, so a build never waits for one. A hook may still be written
* `async`: a promise it returns is left to run on its own, and a rejection is
* caught and reported rather than reaching the host as an unhandled one. A
* hook that throws is reported and does not fail the build that called it.
*
* They return `Promise<void> | void` rather than `void` for that reason. Both
* accept an `async` hook as far as the compiler is concerned, but `void` alone
* makes one a `no-misused-promises` error under the type-aware lint rules a
* consumer is likely to be running — for a hook this documents as supported.
*
* Rolldown's watch mode rebuilds on macOS as well, a token reached through a
* symbolic link included. Its watcher there drops the events for a path
* registered through a link — a workspace package linked into `node_modules`,
* or a project under `/var` or `/tmp`, both links on macOS — so each such path
* is registered by its realpath beside it, and the event is mapped back to the
* spelling the `source` patterns use.
*/
export interface UnpluginStyleDictionaryOptions {
/**
* Whether a configuration whose output is already up to date may skip its
* compile.
*
* A build's expensive half is `buildAllPlatforms` — around 80% of it on a
* 4,000-token, two-platform configuration — and under Vite it runs inside
* `server.listen()`, so the dev server does not accept a connection until
* it finishes whether or not a token changed. A configuration is treated as
* up to date when every file its last compile wrote exists and is as that
* compile left it, and nothing it reads, its own config file included, has
* changed since that compile read it. A file it declares and Style
* Dictionary declined to write — a filter matching no tokens — does not stop
* it being skipped, since that file was never going to be there.
*
* "Since" means since the moment that compile began reading, so a token
* saved while a rebuild is compiling is rebuilt rather than taken for part
* of the output the rebuild went on to write. What each compile read is
* kept in `node_modules/.cache/unplugin-style-dictionary` beside the nearest
* `package.json`, so a restart still knows it. Where nothing is recorded,
* the files a configuration reads are compared against the files it
* declares instead.
*
* A compile is also recorded against the configuration that ran it: its
* contents, the hooks it names as Style Dictionary's registry holds them —
* each `format`, `filter`, `fileHeader`, transform, transform group,
* parser and preprocessor it refers to by name — and the Style Dictionary
* version. A new body registered under a name it uses, or an upgrade,
* rebuilds even though no file moved. What a hook's code calls from another
* module is not part of that code, so an edit there is not seen; naming the
* module in `watch` makes the next start rebuild.
*
* Two things are never skipped, because neither can be told from the
* filesystem:
*
* - **The first compile of a process, for a configuration given as an
* object or a function.** There is no config file to stat, so an edit to
* the object inside `vite.config.ts` moves no mtime. Within one process
* the resolved configuration is compared against the one that was last
* built. An earlier process's record is not trusted for it, because its
* functions are compared by their source and what they close over can
* differ from one process to the next, so it builds.
* - **A platform declaring `actions`.** An action writes what no
* `destination` names, so a skip would leave its work undone.
*
* A custom format that reads something off-disk — an environment variable,
* a network call — cannot be detected this way either, and is what this
* option exists to turn off.
*
* @default true
*/
cache?: boolean
/**
* Style Dictionary configuration(s).
* Can be:
* - A file path string (e.g. 'sd.config.json')
* - An array of file path strings
* - A Style Dictionary configuration object
* - An array of Style Dictionary configuration objects
* - A function that returns a config or array of configs (or resolves to them).
* Useful for calling `StyleDictionary.registerFormat()` (or other `register*`
* methods) before returning a config that references the custom format by name.
* It is handed a `StyleDictionaryConfigContext` describing what the host is
* doing, so an expensive platform can be built only when it is wanted —
* skipped under the dev server, built by `vite build`. A function taking no
* arguments stays valid: TypeScript accepts one of fewer parameters, and
* JavaScript ignores the extra argument.
*
* If not provided, the root directory is searched for 'sd.config.json',
* 'config.json', 'sd.config.js' and 'sd.config.mjs', in that order. The
* first one that *looks like a Style Dictionary configuration* wins — it has
* to declare at least one of `platforms`, `source`, `include` or `tokens` —
* and the path it picked is announced, so which file a build used is
* answerable from the console. A candidate that fails that check is skipped
* rather than adopted, because `config.json` is an extremely common name for
* something else entirely. It is named in that announcement when a later
* candidate is adopted, and reported as an error when none is.
*
* **`false` turns discovery off.** Two of the four names are modules rather
* than data, and reading a module means running it: a `sd.config.js` in the
* root is imported when it is first read, and again whenever it or a file
* named in `watch` changes. Validation cannot prevent that, because the
* check can only look at what the import returned — so a
* project that names its configuration explicitly, or has none, should say
* `config: false` rather than rely on there being nothing to find.
*/
config?:
| ((
context: StyleDictionaryConfigContext,
) => Config | Config[] | Promise<Config | Config[]>)
| Config
| Config[]
| false
| string
| string[]
/**
* Whether a failed rebuild is pushed to Vite's error overlay.
*
* A rebuild that fails under the dev server used to reach the browser
* nowhere: the page went on rendering the last good generated file, and the
* only trace was one red terminal line the developer may not have been
* looking at. With this on, the failure is sent to the page as an error
* frame naming this plugin, and the overlay is dismissed on the next
* rebuild that succeeds.
*
* This is Vite's overlay, so it does nothing on the other four targets,
* and nothing under `vite build` — there is no page to draw on.
*
* It is not `failOnError`'s job, and the two are independent. `failOnError`
* decides whether the host stops; this decides whether the browser is told.
* A dev server deliberately keeps serving through a failed rebuild, which is
* precisely the case where the overlay is the only thing that can say so.
*
* A token file that fails to parse is reported like any other failed
* compile: it reaches the overlay, and `onBuildError`, with the parser's
* message.
*
* @default true
*/
errorOverlay?: boolean
/**
* Whether a compile that fails should throw rather than only be reported.
*
* A failed compile used to be logged and swallowed, so `vite build`,
* `rollup` and `webpack` all exited 0 and shipped whatever the previous
* run had written — the stale values, presented as current.
*
* - `'build'` (the default) throws on the one-shot compile that runs in
* `buildStart`, and only reports a failed watch rebuild, so a dev server
* survives a half-typed token file.
* - `'serve'` is the reverse: a failed rebuild is thrown to whatever awaited
* it, which is the host under `rollup --watch`. Vite's dev server has no
* build to fail, so there it is reported and the server keeps serving.
* - `true` throws on both, `false` on neither.
*
* Reporting happens either way, and is not suppressed by `silent`.
*
* Any other value throws a `TypeError` when the plugin is created — the
* string `'true'` from an environment variable included, which used to
* behave as `false`.
*
* @default 'build'
*/
failOnError?: 'build' | 'serve' | boolean
/**
* How much this plugin and Style Dictionary say while building.
*
* Style Dictionary's own warnings — a name collision, a reference that
* cannot be resolved, `No tokens for vars.css. File not created.` — used to
* be suppressed unconditionally, because the plugin overwrote
* `log.verbosity` on the way past. Leave this unset and whatever the
* configuration asked for stands.
*
* - `'silent'` — nothing from either.
* - `'warn'` — Style Dictionary's warnings, and nothing from the plugin.
* - `'info'` — the above, plus the plugin's progress lines and size table.
* - `'verbose'` — the above, with Style Dictionary naming what it warned
* about rather than pointing at its own `--verbose` flag.
*
* A compile that fails is reported at every level, so there is no
* `'error'`: `'silent'` is the quietest and still reports a failure. Any
* other value, `'error'` included, throws a `TypeError` when the plugin is
* created.
*
* This option governs what the plugin says, not where it goes. The messages
* are handed to the host — Vite's `config.logger`, the rollup and rolldown
* plugin context, webpack's `compilation` — so a host silenced by its own
* log level suppresses them after this option has let them through. A
* failure still stops the build whenever `failOnError` says it should,
* printed or not.
*
* @default undefined, which prints the plugin's own lines and leaves the
* configuration's `log.verbosity` alone
*/
logLevel?: 'info' | 'silent' | 'verbose' | 'warn'
/**
* Called once a build has finished, with every file it declares that is on
* disk and how long it took in milliseconds.
*
* The paths are absolute and platform-native, sorted so two runs of the same
* configuration hand back the same order. They are what the build declares
* rather than what it wrote this time: a configuration skipped by `cache`
* contributes its destinations too, because they are on disk and current,
* and a post-processing step that ignored them would leave half the output
* untouched on a rebuild that changed one file. A declared file Style
* Dictionary declined to write — a filter matching no tokens — is left out,
* since there is nothing there to open.
*
* This is where formatting the generated files, type-checking them, or
* telling something else they have landed belongs.
*
* @default undefined
*/
onBuildEnd?: (files: string[], durationMs: number) => Promise<void> | void
/**
* Called when a build fails, with whatever was thrown.
*
* A failure inside Style Dictionary arrives wrapped in an `Error` whose
* message names the configuration it came from, with Style Dictionary's own
* error as its `cause`. One the plugin raises itself already names it.
*
* It fires whatever `failOnError` is set to, and before that option decides
* whether to rethrow — the two answer different questions, and under a dev
* server the default is not to throw at all.
*
* The failure is reported to the console either way, so this is for reacting
* to one rather than for noticing it.
*
* @default undefined
*/
onBuildError?: (error: unknown) => Promise<void> | void
/**
* Called before a build begins, once per build.
*
* A watch-triggered rebuild is a build, so this fires again for each one.
*
* @default undefined
*/
onBuildStart?: () => Promise<void> | void
/**
* Which platforms to build, by the names the configuration defines.
*
* Every rebuild used to compile every platform. Measured on a six-platform
* configuration (css, scss, js, ios, android, flutter), with the timer around
* the build call alone:
*
* ```
* tokens all platforms css only saved
* 500 12 ms 1 ms 10 ms
* 3000 36 ms 2 ms 34 ms
* 10000 103 ms 4 ms 99 ms
* 30000 330 ms 12 ms 319 ms
* ```
*
* So a dev server serving a web app paid for Objective-C headers, Android
* XML and Dart classes on every token save, and the cost grows with the
* token count.
*
* Two shapes. An array selects the same platforms for every build. An object
* splits the first compile from the watch rebuilds, which is the common
* want — build everything once, then rebuild only what the page uses:
*
* ```typescript
* platforms: ['css']
* platforms: { watch: ['css'] }
* ```
*
* An omitted key means every platform, so `{ watch: ['css'] }` builds all of
* them once and then only css. A name the configuration does not define is an
* error, matching Style Dictionary's own CLI — "Must be defined in the
* config".
*
* **Unselected platforms keep whatever they last wrote.** Their files are not
* removed and not refreshed, so a one-shot build that scopes platforms ships
* stale output for the rest. Scope the watch half rather than the build half
* unless that is what you want.
*
* Any other shape throws a `TypeError` when the plugin is created: a single
* string, or an object with a key other than `build` and `watch` — `serve`
* is the easy slip, since `failOnError` says `'serve'`. Both used to build
* every platform.
*
* @default undefined, which builds every platform
*/
platforms?: string[] | { build?: string[]; watch?: string[] }
/**
* Whether the table of generated files and their sizes is produced.
*
* Every generated file is read in full and gzipped at level 6 to fill the
* `gzip:` column — 4.5ms for 515kB of output, and 21ms at 6MB. That is
* small beside the compile it follows, and it is pure cost to a project
* large enough to care.
*
* This is not `logLevel`'s job, and the two differ in what they leave
* standing. `logLevel: 'warn'` silences the plugin's progress lines along
* with the table; `report: false` keeps them and drops only the table,
* along with the read and the compression behind it.
*
* Dropping to gzip level 1 instead was measured and rejected: it reported a
* figure up to 8.7% off — 21.4kB against 19.7kB on the same JSON — and that
* number is one a consumer compares against their own bundler's report.
*
* @default true
*/
report?: boolean
/**
* The directory a relative `config` path is looked up in, and a relative
* `watch` entry is resolved against.
*
* Defaults to the host's own root — Vite's `root`, webpack's `context` —
* and to the working directory for rollup and rolldown, which offer none.
* A relative value here is resolved against the working directory, and it
* takes precedence over whatever the host reports.
*
* It does not move the paths **inside** a configuration. Style Dictionary
* resolves every relative `source`, `include` and `buildPath` against the
* working directory, and this plugin reads them the same way, so a
* configuration behaves identically here and under Style Dictionary's own
* CLI. A configuration kept in a subdirectory therefore names its tokens
* relative to where the build runs, not relative to itself.
*/
root?: string
/**
* Disable console logging.
*
* An alias for `logLevel: 'silent'`, which wins if both are set. A compile
* that fails is always reported.
*
* @default false
*/
silent?: boolean
/**
* Additional files or glob patterns to watch, on top of what is watched
* already: a `config` given as a path, and every file matched by the
* `source` and `include` patterns inside each configuration.
*
* Patterns are expanded to the paths they match before being registered,
* because the watchers in play take filenames rather than patterns. A
* pattern's own directory is registered alongside them, so a token file
* created later is noticed too.
*
* A relative entry is resolved against `root`, like a relative `config`: both
* are options of this plugin rather than paths inside a configuration. That
* is not the base `source` and `include` use — Style Dictionary reads those
* against the working directory — so where the host's root is somewhere
* else, name a file here relative to the root, and in `source` relative to
* where the build runs.
*
* A configuration module is imported again when a file named here changes,
* so a data file it reads when it loads is picked up. A module that a
* configuration or a token module itself imports is evaluated once per
* process, though: naming it here buys a rebuild, not a re-read.
*
* What a change to a watched file then triggers is the host's to decide —
* see the interface documentation above.
*/
watch?: string | string[]
}Migrating from vite-plugin-style-dictionary
This package was previously published as
@kanso-labs/vite-plugin-style-dictionary, implemented directly as a Vite
plugin. As of this unplugin-based rewrite:
- The package is renamed to
@kanso-labs/unplugin-style-dictionary. - The root import no longer resolves to a ready-to-use Vite plugin. Import the
bundler-specific entry point instead:
@kanso-labs/unplugin-style-dictionary/vite(a drop-in replacement for the old default export),/rolldown,/rollup, or/webpack. - The exported options type is renamed from
VitePluginStyleDictionaryOptionstoUnpluginStyleDictionaryOptions. The shape of the options (config,watch,silent) is unchanged. It is exported from every entry point, so it comes from the same specifier as the plugin:import type { UnpluginStyleDictionaryOptions } from '@kanso-labs/unplugin-style-dictionary/vite'. - Behavior under Vite is unchanged: the same
buildStart-time compilation and dev-server watch/rebuild logic as before.
Development
Fork, then clone the repository:
git clone https://github.com/your-username/unplugin-style-dictionary.gitInstall with the Node version in .tool-versions. CI resolves
it from that file, and an older npm rewrites package-lock.json as it installs.
If node --version disagrees:
mise exec node@"$(awk '/^nodejs/{print $2}' .tool-versions)" -- npm installThe four commands
These are what CI runs, and between them they are the whole gate:
npm run lint # oxlint, then ESLint, then oxfmt --check
npm run build # tsc -b, then tsdown into dist/
npm test # vitest, one run, no watch
npm run package:check # publint, attw, then scripts/check-package.mjsnpm run package:check reads dist/, so it needs a build first.
npm run peers:check is the slower one that packs the tarball and builds it
against both ends of every declared peer range; Build runs it, and it is worth
running locally when you touch the exports map or the peer declarations.
oxfmt formats this repository, not Prettier, and it covers Markdown, JSON
and YAML as well as TypeScript. npm run lint -- --fix will not reformat
anything — reach for npm run format.
Tests
tests/ drives real bundlers against real files in temporary directories rather
than mocking Style Dictionary: a real Vite dev server, a real rollup.watch(),
a real webpack() compile, a real rspack() compile, and all five targets
through their own entry points. A new hook needs a matching caller in
tests/index.test.ts — calling one bare leaves this undefined and the failure
reads as a plugin bug.
The suite prints nothing. If you add a test that provokes the plugin's failure
report, spy on console.error, assert the message is there, and restore in
a finally. You can check the whole suite is quiet with:
npx vitest run --reporter=verbose 2>&1 | grep -E '^std(out|err) \|'That should print nothing.
AGENTS.md carries the conventions, the traps, and the reasoning
behind both. It is written for coding agents and is equally the fullest thing a
human contributor can read.
Contribution guidelines for the organization are in
kanso-labs/.github.
License
MIT
