如何配置Style Dictionary生成嵌套结构的theme.js文件?
解决Style Dictionary生成嵌套结构theme.js的问题
问题分析
你遇到两个核心问题:
TypeError: StyleDictionary.extend is not a function:因为你的package.json设置了"type": "module",但配置文件用了CommonJS语法(require/module.exports),导致模块加载异常。- 无法保留嵌套结构:默认的
jstransformGroup会扁平化token,且自定义formatter未处理$value的嵌套节点。
解决方案步骤
1. 适配ES模块语法
由于package.json启用了ES模块,配置文件config.js必须改用ES模块语法:
- 用
import替代require - 调用
StyleDictionary.extend()加载配置并主动执行构建
2. 编写自定义格式化逻辑
添加递归函数处理token结构,提取$value字段值,同时保留原始嵌套层级。
3. 调整transform配置
避免使用默认的js transformGroup(会触发扁平化),只保留必要的transform以维持结构。
最终配置文件(config.js)
import StyleDictionary from 'style-dictionary'; // 递归处理token,提取$value并保留嵌套层级 function processNestedTokens(tokens) { const processed = {}; for (const key in tokens) { if (tokens[key].hasOwnProperty('$value')) { processed[key] = tokens[key].$value; } else { processed[key] = processNestedTokens(tokens[key]); } } return processed; } // 注册自定义嵌套格式 StyleDictionary.registerFormat({ name: 'javascript/nested', formatter: ({ dictionary }) => { const nestedTheme = processNestedTokens(dictionary.tokens); return `export const theme = ${JSON.stringify(nestedTheme, null, 2)};`; }, }); // 加载配置并执行构建 StyleDictionary.extend({ source: ['tokens/**/*.json'], platforms: { js: { // 仅保留维持结构的transform,避免扁平化 transforms: ['attribute/cti'], buildPath: 'build/js/', files: [ { destination: 'theme.js', format: 'javascript/nested', }, ], }, }, }).buildAllPlatforms();
验证效果
执行npm run build后,build/js/theme.js会生成你预期的嵌套结构:
export const theme = { colors: { primary: { light: "#FFCC00", dark: "#FF9900" }, secondary: { light: "#00CCFF", dark: "#0066FF" } } };
额外注意
确保已安装Style Dictionary依赖:
npm install style-dictionary --save-dev
内容的提问来源于stack exchange,提问作者ando
相关产品推荐
相关产品推荐

