Init a single source of truth for tokens and wire a clean configjson-driven workflow to keep naming consistent across platforms. Write tokens once in the repo and extend through color and typography scales with style-dictionary-utils.
Within the repo, define a tight set of variables for color, spacing, and typography. If you are adding new tokens, maintain a clear naming pattern like colors.primary, font.body, and spacing.grid. You can find tokens via your source tree and automate updates with a simple write workflow that outputs JSON for web and mobile targets.
To enable cross-platform theming, use the init flow to import base tokens and then extend for each platform. The style-dictionary-utils map tokens to transforms for platform formats, so you can adding platform-specific transforms without duplicating definitions.
Keep the configjson entry minimal and explicit; declare colors, typography, and semantics in one place, then publish results through the build step. This approach helps teams have consistent themes shipped quickly and securely.
Ready to level up your UI system? Browse the repo, review the naming conventions, and start writing tokens that scale across web, iOS, and Android with Style Dictionary: Design Tokens for Cross-Platform Theming.
Install Guide: Quick Start for Web, iOS, and Android Projects
Install Style Dictionary with npm i -D style-dictionary, then create a minimal tokens file and a config that covers web, iOS, and Android outputs. Note that the configuration should emit CSS variables for web, Swift constants for iOS, and colors.xml for Android in one run. Use metadata to annotate tokens with origin, notes, and design intent; comments help teammates review decisions, thats useful for audits. Because tokens may reference each other, enable transitive references and use shouldoutputref to keep values consistent across platforms. Keep colorarray palettes clearly defined and tag tokens with a styledictionarycolor type when relevant. Use exports to expose values to downstream projects and organize your files into folders by platform and type so teammates can find what they need quickly. Start with a playground to preview values, and base typography on 1rem to maintain consistent sizing across outputs.
Web quick start: add a platforms.web section to sd.config.json and emit a tokens.css file at build/web/tokens.css. Map color tokens to CSS custom properties like --color-primary and --color-neutral-900, applying a normal naming scheme that mirrors the token path (e.g., color.primary, color.gray.900). For web, keep the CSS output lightweight, and expose a reference to color tokens so design decisions remain traceable via metadata. If you plan to reuse colors in UI frameworks, consider exporting a JS module as part of the same run to simplify integration, and use the styledictionarybuildallplatforms script alias to test end-to-end across all targets.
iOS quick start: configure the ios platform to generate a Swift file (Colors.swift or Tokens.swift) containing a struct with static constants for each color token. Example: static let colorPrimary = UIColor(named: "color_primary") or a direct hex initializer. Leverage transitive token references to keep palettes aligned, and mark values with styledictionarycolor for clarity in the playground. Ensure the output aligns with normal iOS color handling and includes a note in metadata to explain the design rationale. This approach keeps what users see consistent with the design system while simplifying code reviews and theming experiments.
Android quick start: set up the android platform to output colors.xml with entries like
| Step | Command / Output |
|---|---|
| 1. Install | npm i -D style-dictionary |
| 2. Prepare tokens | Create tokens/colors.json (or colors.yaml) with entries like "color": { "primary": { "value": "#FF3B30" } }; add comments to explain usage and set type to styledictionarycolor where applicable |
| 3. Configure | sd.config.json with platforms.web, platforms.ios, platforms.android; define buildPath and output files for each target; enable transitive references |
| 4. Build | npx style-dictionary build; or npm run styledictionarybuildallplatforms if you added a script alias |
| 5. Validate outputs | Web: build/web/tokens.css; iOS: build/ios/Colors.swift; Android: build/android/colors.xml; check color parity and metadata |
Token Modeling: Naming, Scopes, and Platform Specifics
Adopt platform-aware naming from the start: prefix tokens by platform and scope to keep cross-platform theming consistent. Use a single references map and maintain a flattened output per platform because a clear naming scheme reduces drift as formats evolve. This approach will streamline integration and relies on build-tokensjs to drive the pipeline across projects.
Name tokens with a stable, readable pattern: include base tokens such as color, size, and typography; use sizefontbase as the canonical font-size base token. Combine a category, a token role, and a platform suffix (for example button.size or text.color) so the same token name transforms cleanly when you switch formats. This means you can import a single source of truth and outputting per platform becomes straightforward.
Define scopes clearly: global handles system defaults; components cover UI primitives; themes map to palettes; define per-platform overrides within a platform scope (web, ios, android). The flattened structure helps when you generate references for code, ensuring tools can read them without parsing nested trees. Use filtering to prune unused tokens and keep the surface area tight, then document references in a central reference file for designers and developers.
Formats and tooling: choose formats that align with your framework and build environment. For cross-platform theming, javascriptesm modules support tree-shaking and easy import into web apps and native shells. Outputting the same tokens to multiple formats–json, style dictionary, and css variables–reduces friction in integration. Options include per-platform outputs, partial builds, and a grunt-driven watch that rebuilds on change. The toolchain should keep style tokens cohesive across platforms, while still allowing platform-specific overrides.
Workflow practices: define tokens with stable names, maintain a flattened reference map, and use filtering to avoid bleed of platform-specific quirks. Generate artifacts with build-tokensjs, then consume via javascriptesm streams in your app. Because the map is well-structured, teams can add new formats without breaking existing integrations, saving time and reducing errors.
Create Core Tokens: Colors, Typography, Spacing, and Shadows
Define core tokens now: Colors, Typography, Spacing, and Shadows as a single source of truth and publish them to every platform.
Colors define a colorbasegraydark baseline, with tokens for neutrals and accents. Store them in an nsarray for quick lookup, and assign a signed hex value to each. The system uses uicolor for iOS and emits CSS variables for the web, with a comment field describing usage. It will provide options for light and dark variants and returns color values in hex, rgba, or packed integer formats. The spec tells developers how to map tokens.
Typography tokens establish font families, weights, sizes, and line heights with a deep size scale. A function named dimensionpixeltorem converts pixel metrics to rem-based values. The nodejs tooling consumes starter templates and emits cross-platform typography definitions, plus comment blocks describing usage.
Spacing uses a deep size scale for margins, paddings, and gaps: 4, 8, 12, 16, 24, 32, 48. The spacing tokens feed into a transformgroup that composes layout blocks. From this single source you generate per-component spacings via templates.
Shadows encode depth with signed offsets, blur radii, and color derived from colorbasegraydark. Each shadow token maps to an elevation level and uses a color referenced from the base gray. The pipeline returns CSS box-shadow values and platform-specific representations for uicolor on iOS. Add comment for usage, and provide options to layer shadows over elements.
To operationalize, build a starter JSON that defines colors, typography, spacing, and shadows. The toolchain will call a transformer to produce CSS variables, Swift/ObjC UIColor values, and Android styles. From the JSON, a nodejs script returns a set of artifacts.
Take this approach and tie it to templates in your design system; the result is a cohesive starter that grows with your product and has been proven to streamline updates. This would stabilize theming across teams.
Migrate Legacy Tokens: Mapping Strategy and Common Pitfalls
Export your legacy tokens to configjson and map them to formatsscssvariables for immediate cross-platform theming.
Treat font_dimensxml as the typography baseline: capture font sizes, line heights, font weights, and family aliases in a basic token group feeding html and framework components.
Set up a mapping workflow that outputs two artifacts: html-ready tokens and typescriptesm-declarations, with a dedicated project to validate the results. Follow with a CI check using yarn and a small sample page.
Mapping Strategy
Define source categories: color, typography, spacing, and headers; keep headers tightly scoped to preserve semantic naming across platforms.
Align naming across configjson and the target outputs: formatsscssvariables for CSS, and a TS interface for javascriptesm and typescriptesm-declarations. Use styledictionaryregistertransform to enforce naming, and wire it to yarn scripts so you can run the transform in both modes from the root project. Looking at the following steps: 1) normalize naming, 2) generate outputs, 3) test against a small sample page. Looking across categories and looking for gaps; dont skip any step and avoid a process that feels like guesswork.
Recherchez les chevauchements et assurez-vous d’une source unique de vérité ; faites en sorte que chaque jeton soit renvoyé à son origine dans font_dimensxml ou les définitions de couleurs afin d’éviter les dérives entre les plateformes. Vers le bas et assurez-vous d’une cohérence globale.
Pièges courants
Les jetons manquants dans le format cible provoquent des lacunes au moment de l'exécution ; vérifiez que les jetons font_dimensxml, les en-têtes et les jetons de couleur existent à la fois dans configjson et formatsscssvariables avant la publication.
Des échelles incohérentes nuisent à la thématique ; verrouillez les échelles de typographie et les rampes de couleurs au niveau de base et propagez ces choix aux jetons en aval.
La sur-automatisation sans validation invite des régressions ; maintenez une page de test au niveau du projet pour rendre les jetons et confirmer que la correspondance est conforme aux attentes du framework.
Construire, Valider et Prévisualiser : CLI, Configurations et Assurance Qualité Visuelle
Exécutez yarn build-tokensjs à la racine du projet pour générer le fichier aplati dans le répertoire suivant : tokens/outputting. L’interface de ligne de commande lit votre configuration et écrit une carte de jetons statique que vous pouvez réutiliser sur plusieurs plateformes.
Load the config with the option --config path/to/config.json to keep the build deterministic and open the door for consistent results across teams.
- Build : À partir de la racine, la commande parcourt l'arborescence des fichiers à travers la structure des répertoires pour regrouper les jetons par portée ; elle produit un fichier JSON statique aplati et écrit les ressources dans tokens/outputting. La construction prend en charge scssmap-deep pour générer une carte SCSS profonde, et elle fait référence aux jetons tels que bodythemedark et styledictionarycolorh dans les groupes de couleurs.
- Valider : Exécuter une étape de validation qui vérifie les champs obligatoires, la dénomination des jetons et l'existence des chemins ; lorsque un groupe de jetons est manquant, l'outil signale le chemin manquant et vous permet de le corriger avant d'attendre une nouvelle exécution. Ceci garantit que le fichier est conforme à la configuration et à la structure prévue.
- Aperçu : Ouvrez une page de contrôle qualité visuel qui affiche les jetons sous forme d'échantillons et de variables CSS ; l'aperçu statique lit la sortie et affiche les jetons dans un scénario que vous ajoutez, afin que vous puissiez confirmer le contraste, le regroupement et la typographie dans une interface utilisateur simple. Utilisez le chemin fourni pour ouvrir l'aperçu à http://localhost:8080/preview.
Note d'automatisation : ayez un flux de travail léger qui appelle build-tokensjs, puis exécute une validation distincte, puis génère l'aperçu ; vous pouvez ajouter des jetons supplémentaires comme buildts et décrire comment chaque jeton se mappe à un composant d'interface utilisateur tel que bodythemedark ou styledictionarycolorh.
Stratégies de Thèmes : Clair/Sombre, Bascule de Thèmes et Substitutions à l'Exécution
Commencez par une seule source de vérité : implémentez les jetons clair et foncé en tant que variables CSS et exposez-les via l'attribut de données `data-theme` sur l'élément racine. Utilisez variablesscss pour lier les jetons aux variables, et connectez-les à votre mystyledictionary token nommé styledictionarycolorkt pour les valeurs de couleur.
Structurez vos données dans le dépôt avec des modèles pour les fichiers de jetons et des globs qui collectent les données dans différents formats. Conservez une carte profonde des jetons et maintenez une scssmap-deep qui reflète la hiérarchie afin que les composants puissent accéder aux jetons de couleurs, de typographie et d'espacement sans coder en dur les valeurs. Incluez des métadonnées et un indicateur showfileheader pour documenter les modifications, et conservez les jetons de base en place afin que la mise en page reste prévisible avec le temps. La configuration privilégie une sortie conviviale pour HTML tout en restant agnostique en matière de langue dans le modèle de données.
Theme switching proceeds with a small, fast script that toggles the root data-theme attribute, then reflows only the affected styles. Respect OS preferences by reading matchMedia('(prefers-color-scheme: dark)'), and provide a user-facing option in templates to store the choice in localStorage so the setting survives reloads.
Les remplacements au moment de l'exécution vous permettent d'étendre un ensemble de jetons au niveau du composant sans modifier le thème de base. Utilisez des attributs de données ou des remplacements de variables CSS en ligne pour pointer vers une palette différente pour une boîte de dialogue, une carte ou une fenêtre modale. Lorsque vous effectuez un remplacement, étendez les jetons existants au lieu de les remplacer, afin de conserver les jetons mystyledictionary d'origine et de simplement remplacer les valeurs au point d'utilisation.
Implementation notes
Dans la configuration du projet, activez les métadonnées incluses, conservez le mappage scssmap-deep et utilisez showfileheader pour annoter les changements. Maintenez une source unique de vérité pour la couche de données et assurez-vous que la sortie HTML est alignée avec la couche CSS. Utilisez une nomenclature claire et un ensemble minimal de modèles afin de réduire la dérive entre les plateformes et les échelles de temps, et assurez-vous que le dépôt est fourni avec un exemple prêt à l'emploi qui démontre comment connecter html, les variables CSS et les données de jeton.




