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';
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: async ({ dictionary, file, options }) => {
const { outputReferences } = options;
const header = await fileHeader({ file });
return (
header +
':root {\n' +
formattedVariables({ format: 'css', dictionary, outputReferences }) +
'\n}\n'
);
},
});

Here are the available format helper methods:

createPropertyFormatter

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.allTokensTransformedToken[]Flattened array of all tokens, easiest to loop over and export to a flat format.
options.dictionary.tokensTransformedTokensAll tokens, still in unflattened object format.
options.dictionary.unfilteredTokensTransformedTokensAll tokens, 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.

Example:

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

fileHeader

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'.
options.commentPositionstring'above' or 'inline', so either above the token or inline with the token
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
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: async ({ dictionary, file }) => {
const header = await fileHeader({ file, commentStyle: '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.


formattedVariables

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

ParamTypeDescription
optionsObject
options.formatstringWhat type of variables to output. Options are: 'css', 'sass', 'less', and 'stylus'.
options.dictionaryDictionaryTransformed Dictionary object containing allTokens, tokens and unfilteredTokens.
options.dictionary.allTokensTransformedToken[]Flattened array of all tokens, easiest to loop over and export to a flat format.
options.dictionary.tokensTransformedTokensAll tokens, still in unflattened object format.
options.dictionary.unfilteredTokensTransformedTokensAll tokens, still in unflattened object format, including tokens that were filtered out by filters.
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.formattingObjectCustom formatting properties that define parts of a comment in code. The configurable strings are: prefix, lineSeparator, header, and footer.
options.themeablebooleanWhether tokens should default to being themeable. Defaults to false.

Example:

build-tokens.js
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: function ({ dictionary, options }) {
return formattedVariables({
format: 'less',
dictionary,
outputReferences: options.outputReferences,
});
},
});

getTypeScriptType

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
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');
},
});

iconsWithPrefix

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
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: function ({ dictionary, options }) {
return iconsWithPrefix('$', dictionary.allTokens, options);
},
});

minifyDictionary

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
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: function ({ dictionary }) {
return JSON.stringify(minifyDictionary(dictionary.tokens));
},
});

setComposeObjectProperties

Outputs an object for compose format configurations. Sets import.

ParamTypeDescription
optionsObjectThe options object declared at configuration

setSwiftFileProperties

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

sortByName

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
StyleDictionary.registerFormat({
name: 'myCustomFormat',
format: function ({ dictionary, options }) {
return dictionary.allTokens
.sort(sortByName)
.map((token) => `${token.name} = ${token.value}`)
.join('\n');
},
});

sortByReference

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
dictionary.allTokens.sort(sortByReference(dictionary));