@cobalt-ui/plugin-json
This reworks your deeply-nested source tokens.json
into a shallow object with all references resolved and metadata added. Keeps the portability of JSON, but does most of the hard work of parsing the original tokens file for you!
Install
npm i -D @cobalt-ui/plugin-json
import json from '@cobalt-ui/plugin-json';
export default {
plugins: [
json({
filename: './tokens.json',
}),
],
};
Usage
Say you wanted to import your tokens into JS, and get all the color
tokens out of it. Well, how would you? You’d have to:
- Walk through the deep-nested object over every node
- Not only find the
"color"
tokens, but also tokens with no "$type"
that inherit the group type (could be several levels up) - Resolve all references to other values
This plugin does all that for you. It generates an object only 1 level deep, with all the tokens at the top level. For example, to find all color
tokens:
import tokens from './tokens/tokens.json';
const colors = [];
for (const [id, token] of Object.entries(tokens)) {
console.log(id);
console.log(token);
if (token.$type === 'color') {
colors.push(v);
}
}
This expands all values, so every token in a color
group will have $value
explicitly set. And the alias will have been resolved so .$value
will be the actual color value.
All other properties, such as $name
, $description
, and $extensions
, are all preserved intact.
If you needed to reference anything from the original node, this plugin adds an _original
key to each node. This is useful if you wanted to see what the original alias was for.
Transform
Inside plugin options, you can specify an optional transform()
function:
export default {
plugins: [
pluginJSON({
transform(token, mode) {
if (token.$type === 'font') {
return token.$value.replace('sans-serif', 'Brand Sans');
}
},
}),
],
};
Your transform will only take place if you return a string; otherwise the default transformer will take place.
Custom tokens
If you have your own custom token type, e.g. my-custom-type
, you’ll have to handle it within transform()
:
export default {
plugins: [
pluginJSON({
transform(token, mode) {
switch (token.$type) {
case 'my-custom-type': {
return String(token.$value);
break;
}
}
},
}),
],
};