Deisgn tokens concept using Style Dictionary
This example shows how you can manage what tokens are generated and how they are organized. This is useful when you want to generate a 1:1 relationship between build files and token categories.
Common use cases include:
- Each token category as its own Sass partial (_colors.scss)
- Separate component files (button.css, input.css, etc)
- Tree shaking (only import what you need)
First of all, set up the required dependencies running the command npm install
in your local CLI environment (if you prefer to use yarn, update the commands accordingly).
At this point, you can run npm run build
. This command will generate the output file in the build
folder.
The "build" command processes the JSON files in the tokens
folder. The index.js
file adds each folder, allowing you to map through them in config.js
. The script goes through each folder and generates a file for each folder and populates it with tokens that match the filter.
# tokens/color/base.json
{
"color": {
"red": {
"value": "#FF0000"
}
}
}
# tokens/size/base.json
{
"size": {
"small": {
"value": "2px"
}
}
}
Because the folder name matches the category, the output would automatically generate separate color
and size
files.
Open the config.js
file and see how the script first looks within the tokens
directory to map through each folder. The destination then outputs a file that would match the name, and fill that file with the tokens that match the filter criteria.
files: core.map((tokenCategory) => {
return {
destination: `${tokenCategory}.css`,
format: "css/variables",
filter: function (token) {
console.log({ tokenCategory });
console.log(token);
return token.filePath.includes(tokenCategory);
},
};
}),
Now each new folder that gets added will automatically generate a corresponding file filled with tokens that match the category!
- Category
- Subcategory
- Item
- Sub-item
- Variant
- Size
e.g text-body-size-sm
- Item
- Sub-item
- Variant
- Category
- Subcategory
- Size
e.g button-primary-text-color