Skip to content

Instantly share code, notes, and snippets.

@fmal
Last active February 23, 2023 18:47
Show Gist options
  • Save fmal/e5ffc41139f0c433aa36ebb8c248afe1 to your computer and use it in GitHub Desktop.
Save fmal/e5ffc41139f0c433aa36ebb8c248afe1 to your computer and use it in GitHub Desktop.
typescript/module-declarations format
export default function simplifyTokens(obj, mapper = token => token.value) {
const result = {};
for (const key in obj) {
if (!obj[key] || typeof obj[key] !== 'object') {
continue;
}
if ('value' in obj[key]) {
result[key] = mapper(obj[key]);
continue;
}
result[key] = simplifyTokens(obj[key], mapper);
}
return result;
};
StyleDictionary.registerFormat({
name: 'typescript/module-declarations',
formatter: ({ dictionary }) => {
const tokens = dictionary.allTokens.reduce((tokens, token) => {
tokens[token.name] = token.value;
return tokens;
}, {});
return [
'export default tokens;',
`declare const tokens: ${JSON.stringify(tokens, null, 2)};`
].join('\n');
}
});
StyleDictionary.registerFormat({
name: 'typescript/module-declarations',
formatter: ({ dictionary }) => {
const tokens = dictionary.allTokens.reduce((tokens, token) => {
tokens[token.name] = 'string';
return tokens;
}, {});
const output = [
'export default tokens;',
`declare const tokens: ${JSON.stringify(tokens, null, 2)};`
].join('\n');
// JSON stringify will quote strings, because this is a type we need
// it unquoted
return output.replace(/"string"/g, 'string');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment