Implement theming with Tokens Studio PRO
mainIf you are using the PRO version of Tokens Studio, you can integrate its theme data with Style Dictionary using sd-transforms.
To implement this, you must:
- Register
sd-transformswith Style Dictionary usingregister(StyleDictionary, { ... }). - Parse your
$themes.jsonfile. - Map through the themes to create individual Style Dictionary configurations.
- Crucial: Since version 0.16.0, you must explicitly set
preprocessors: ['tokens-studio']in your configuration object. - For each theme, define a platform (e.g.,
css) using thetokens-studiotransformGroupand specify your desiredtransformsandfilesdestination.
import { register } from '@tokens-studio/sd-transforms';
import StyleDictionary from 'style-dictionary';
import { promises } from 'fs';
register(StyleDictionary, {
/* options here if needed */
});
async function run() {
const $themes = JSON.parse(await promises.readFile('$themes.json', 'utf-8'));
const configs = $themes.map(theme => ({
source: Object.entries(theme.selectedTokenSets)
.filter(([, val]) => val !== 'disabled')
.map(([tokenset]) => `${tokenset}.json`),
preprocessors: ['tokens-studio'], // <-- since 0.16.0 this must be explicit
platforms: {
css: {
transformGroup: 'tokens-studio',
transforms: ['name/kebab'],
files: [
{
destination: `vars-${theme.name}.css`,
format: 'css/variables',
},
],
},
},
}));
async function cleanAndBuild(cfg) {
const sd = new StyleDictionary(cfg);
await sd.cleanAllPlatforms();
await sd.buildAllPlatforms();
}
await Promise.all(configs.map(cleanAndBuild));
}
run();