Skip to content

Format Helpers

We provide some helper methods we use internally in some of the built-in formats to make building custom formats a bit easier.

They are accessible at style-dictionary/utils entrypoint.

import StyleDictionary from 'style-dictionary';
import { fileHeader, formattedVariables } from 'style-dictionary/utils';
import { propertyFormatNames } from 'style-dictionary/enums';
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: async ({ dictionary, file, options }) => {
const { outputReferences, sort } = options;
const header = await fileHeader({ file });
return (
header +
':root {\n' +
formattedVariables({
format: propertyFormatNames.css,
dictionary,
outputReferences,
sort, // 'name' | ['name'] | [customFn, 'name'] | (a, b) => number
}) +
'\n}\n'
);
},
});

Here are the available format helper methods:

Creates a function that can be used to format a property. This can be useful to use as the function on dictionary.allTokens.map. The formatting is configurable either by supplying a format option or a formatting object which uses: prefix, indentation, separator, suffix, and commentStyle.

ParamTypeDescription
optionsObjectA single argument to support named parameters and destructuring.
options.outputReferencesboolean | OutputReferencesFunctionWhether or not to output references. You will want to pass this from the options object sent to the format function. Also allows passing a function to conditionally output references on a per token basis.
options.outputReferenceFallbacksbooleanWhether or not to output css variable fallback values when using output references. You will want to pass this from the options object sent to the format function.
options.dictionaryDictionaryTransformed Dictionary object containing allTokens, tokens and unfilteredTokens.
options.dictionary.tokensTransformedTokensAll tokens, still in unflattened object format.
options.dictionary.allTokensTransformedToken[]Flattened array of all tokens, easiest to loop over and export to a flat format.
options.dictionary.tokenMapRecord<string, TransformedToken>All tokens as JavaScript. Map
options.dictionary.unfilteredTokensTransformedTokensAll tokens, still in unflattened object format, including tokens that were filtered out by filters.
options.dictionary.unfilteredAllTokensTransformedToken[]Flattened array of all tokens, easiest to loop over and export to a flat, including tokens that were filtered out by filters.
options.dictionary.unfilteredTokenMapRecord<string, TransformedToken>All tokens as JavaScript Map, still in unflattened object format, including tokens that were filtered out by filters.
options.formatstringAvailable formats are: ‘css’, ‘sass’, ‘less’, and ‘stylus’. If you want to customize the format and can’t use one of those predefined formats, use the formatting option
options.formattingFormattingOptionsCustom formatting properties that define parts of a declaration line in code. The configurable strings are: prefix, indentation, separator, suffix, lineSeparator, fileHeaderTimestamp, header, footer, commentStyle and commentPosition. Those are used to generate a line like this: ${indentation}${prefix}${token.name}${separator} ${prop.value}${suffix}. The remaining formatting options are used for the fileHeader helper.
options.themeablebooleanWhether tokens should default to being themeable. Defaults to false.
options.usesDtcgbooleanWhether tokens use the DTCG standard. Defaults to false

Example:

build-tokens.js
import { createPropertyFormatter } from 'style-dictionary/utils';
import { propertyFormatNames } from 'style-dictionary/enums';
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: function ({ dictionary, options }) {
const { outputReferences } = options;
const formatProperty = createPropertyFormatter({
outputReferences,
dictionary,
format: propertyFormatNames.css,
});
return dictionary.allTokens.map(formatProperty).join('\n');
},
});

This is for creating the comment at the top of generated files with the generated at date. It will use the custom file header if defined on the configuration, or use the default file header.

ParamTypeDescription
optionsObject
options.fileFileThe file object that is passed to the format.
options.commentStylestringThe only options are 'short', 'xml' and 'long', which will use the //, <!-- --> or /* style comments respectively. Defaults to 'long'. There is an enum-like JS object commentStyles available for import.
options.commentPositionstring'above' or 'inline', so either above the token or inline with the token. There is an enum-like JS object commentPositions available for import.
options.formattingObjectCustom formatting properties that define parts of a comment in code. The configurable strings are: prefix, lineSeparator, header, footer and fileHeaderTimestamp.

Example:

build-tokens.js
import { fileHeader } from 'style-dictionary/utils';
import { commentStyles } from 'style-dictionary/enums';
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: async ({ dictionary, file }) => {
const header = await fileHeader({ file, commentStyle: commentStyles.short });
return (
header + dictionary.allTokens.map((token) => `${token.name} = ${token.value};`).join('\n')
);
},
});

Use options.formatting.fileHeaderTimestamp set to true to create a fileHeader that contains a timestamp for when the file was created. This used to be default behavior but was made opt-in to accompany the common use case of Style Dictionary running in Continuous Integration (CI) pipelines, and not wanting to create redundant git diffs just because of the timestamp changing between versions.


This is used to create lists of variables like Sass variables or CSS custom properties

| Param | Type | Description | | ------------------------------------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | options | Object | | | options.format | string | What type of variables to output. Options are: 'css', 'sass', 'less', and 'stylus'. | | options.dictionary | Dictionary | Transformed Dictionary object containing allTokens, tokens and unfilteredTokens. | | options.dictionary.allTokens | TransformedToken[] | Flattened array of all tokens, easiest to loop over and export to a flat format. | | options.dictionary.tokens | TransformedTokens | All tokens, still in unflattened object format. | | options.dictionary.unfilteredTokens | TransformedTokens | All tokens, still in unflattened object format, including tokens that were filtered out by filters. | | options.outputReferences | boolean \| OutputReferencesFunction | Whether or not to output references. You will want to pass this from the options object sent to the format function. Also allows passing a function to conditionally output references on a per token basis. | | options.formatting | Object | Custom formatting properties that define parts of a comment in code. The configurable strings are: prefix, lineSeparator, header, and footer. | | options.themeable | boolean | Whether tokens should default to being themeable. Defaults to false. | | options.usesDtcg | boolean | Whether tokens use the DTCG standard. Defaults to false | | options.sort | SortOption | Optional sorting strategy. Use 'name' to sort alphabetically by token name or a custom comparator function (a: Token, b: Token) => -1 | 1 | 0. You can chain multiple sorters with an array of sorters (e.g., [customFn, 'name']). When outputReferencesistrue, reference-safe ordering is automatically enforced first, and your sort acts as a tie-breaker. Defaults to no sorting. |

Example:

build-tokens.js
import { formattedVariables } from 'style-dictionary/utils';
import { propertyFormatNames } from 'style-dictionary/enums';
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: function ({ dictionary, options }) {
return formattedVariables({
format: propertyFormatNames.less,
dictionary,
outputReferences: options.outputReferences,
sort: options.sort,
});
},
});

Given some value, returns a basic valid TypeScript type for that value. Supports numbers, strings, booleans, arrays and objects of any of those types.

Returns: string - A valid name for a TypeScript type.

ParamTypeDescription
valueanyA value to check the type of.
optionsObject
options.outputStringLiteralsbooleanWhether or not to output literal types for string values

Example:

build-tokens.js
import { getTypeScriptType } from 'style-dictionary/utils';
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: function ({ dictionary, options }) {
return dictionary.allTokens
.map(function (prop) {
var to_ret_prop = 'export const ' + prop.name + ' : ' + getTypeScriptType(prop.value) + ';';
if (prop.comment) to_ret_prop = to_ret_prop.concat(' // ' + prop.comment);
return to_ret_prop;
})
.join('\n');
},
});

This is used to create CSS (and CSS pre-processor) lists of icons. It assumes you are using an icon font and creates helper classes with the :before pseudo-selector to add a unicode character. You probably don’t need this.

ParamTypeDescription
prefixstringCharacter to prefix variable names, like $ for Sass
allTokensTransformedToken[]Flattened array of all tokens, easiest to loop over and export to a flat format.
optionsObjectoptions object passed to the format function.

Example:

build-tokens.js
import { iconsWithPrefix } from 'style-dictionary/utils';
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: function ({ dictionary, options }) {
return iconsWithPrefix('$', dictionary.allTokens, options);
},
});

Outputs an object stripping out everything except values

ParamTypeDescription
objTransformedTokensThe object to minify. You will most likely pass dictionary.tokens to it.

Example:

build-tokens.js
import { minifyDictionary } from 'style-dictionary/utils';
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: function ({ dictionary }) {
return JSON.stringify(minifyDictionary(dictionary.tokens));
},
});

Outputs an object for compose format configurations. Sets import.

ParamTypeDescription
optionsObjectThe options object declared at configuration

Outputs an object with swift format configurations. Sets import, object type and access control.

ParamTypeDescription
optionsObjectThe options object declared at configuration
objectTypestringThe type of the object in the final file. Could be a class, enum, struct, etc.
optionsstringThe transformGroup of the file, so it can be applied proper import

A sorting function to be used when iterating over dictionary.allTokens in a format.

Returns: Integer - -1 or 1 depending on which element should come first based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

ParamTypeDescription
aanyfirst element for comparison
banysecond element for comparison

Example:

build-tokens.js
import { sortByName } from 'style-dictionary/utils';
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: function ({ dictionary, options }) {
return dictionary.allTokens
.sort(sortByName)
.map((token) => `${token.name} = ${token.value}`)
.join('\n');
},
});

A function that returns a sorting function to be used with Array.sort that will sort the allTokens array based on references. This is to make sure if you use output references that you never use a reference before it is defined.

ParamTypeDescription
dictionaryDictionaryTransformed Dictionary object containing allTokens, tokens and unfilteredTokens.
dictionary.allTokensTransformedToken[]Flattened array of all tokens, easiest to loop over and export to a flat format.
dictionary.tokensTransformedTokensAll tokens, still in unflattened object format.
dictionary.unfilteredTokensTransformedTokensAll tokens, still in unflattened object format, including tokens that were filtered out by filters.

Example:

build-tokens.js
import { sortByReference } from 'style-dictionary/utils';
dictionary.allTokens.sort(sortByReference(dictionary));

A utility which formats any JS content as a string, using Prettier. Uses default Prettier settings, currently with no way to pass a config. PRs for that feature are welcome.

ParamTypeDescription
contentstringJS content as a string.
tsbooleanWhether JS content is using TypeScript. false by default

Example:

build-tokens.js
import { formatJS } from 'style-dictionary/utils';
const formattedJSContent = formatJS(`const a = 'foobar';`);
const formattedTSContent = formatJS(`const a: string = 'foobar';`, true);

A helper, very similar to stripMeta, that removes meta props that Style Dictionary has added during parsing, preprocessing and transforming the tokens. The main difference with stripMeta is that this one acts as a wrapper and sets default properties to strip away. By default, those properties are: ['attributes', 'filePath', 'name', 'path', 'comment'].

Note that in order for this utility to do anything at all, options.stripMeta has to be set. If it is undefined or false, nothing happens. This is because of how it is used in some formats, where stripping must be an explicit opt-in.

You can pass some options to customize the properties to keep, strip, or whether to use DTCG syntax or not. Be careful if you use the keep option, any property that’s not in this array will get stripped.

ParamTypeDescription
tokensTransformedTokensTransformed Dictionary object. Does not yet support Token Map or Array (PR welcome).
options{ stripMeta?: { strip?: string[], keep?: string[] }, usesDtcg?: boolean }Options object for the stripMetaProps utility.
options.usesDtcgbooleanWhether or not to use DTCG format. false by default.
options.stripMeta{ strip?: string[], keep?: string[] }stripMeta object.
options.stripMeta.stripstring[]List of property keys to strip from the token object.
options.stripMeta.keepstring[]List of property keys to keep in the token.

Example:

build-tokens.js
import { stripMetaProps } from 'style-dictionary/utils';
const tokens = stripMetaProps(dictionary.tokens, { usesDtcg: true, stripMeta: true });
const tokens2 = stripMetaProps(dictionary.tokens, {
usesDtcg: true,
stripMeta: { keep: ['$value'] },
});