style-dictionary-utils

repository·main·Indexed 42 days ago

https://github.com/lukasoppermann/style-dictionary-utils

A collection of filters, transformers, and formats for Style Dictionary version 6.0.1, specifically designed to simplify working with W3C design tokens. It provides an extended StyleDictionary class pre-configured with utilities for CSS colors, shadows, dimensions, typography, and gradients, as well as specialized formats for ESM, CommonJS, and TypeScript declarations.

Tokens
12.4K
Snippets
48
Records
49
Agent score
52%

What's inside style-dictionary-utils

  1. Use the `css/extended` transform group

    main

    The css/extended transform group is a predefined collection included in this package. It contains all standard css transforms plus: color/css, shadow/css, typography/css, fontFamily/css, fontWeight/number, name/pathToDotNotation, cubicBezier/css, and border/css.

    myStyleDictionary.extend({
      platforms: {
        css: {
          transformGroup: 'css/extended',
          files: [
            {
              // ...
            },
          ],
        },
      },
    })
  2. How to extend StyleDictionary with custom transforms

    main

    You can still register your own custom transformers, but you must use the StyleDictionary class imported from style-dictionary-utils to ensure your custom logic integrates correctly with the utility-enhanced instance.

    // build.ts
    import { StyleDictionary } from 'style-dictionary-utils'
    
    StyleDictionary.registerTransform({
      name: 'transform/pxToRem',
      $type: `value`,
      transitive: true,
      transform: () => // ...
    })
  3. How filters work in Style Dictionary Utils

    main

    Filters are used to include or exclude specific tokens when configuring output files in Style Dictionary. You can use filters in two ways:

    1. As a registered filter: Use the filter's registered name as a string (e.g., "isSource") within your Style Dictionary configuration object.
    2. As an importable function: Import the filter function directly (e.g., isSourceFilter) to use it in custom transformers or directly within platform configurations.

    This allows for both high-level configuration via names and low-level programmatic control via function imports.

    // Using registered filter by name
    myStyleDictionary.extend({
      platforms: {
        ts: {
          files: [{
            filter: "isSource", // ← registered filter name
            // ...
          }]
        }
      }
    });
    
    // Importing and using filter function directly
    import {isSourceFilter} from 'style-dictionary-utils/filter/isSource.js'
    
    // Use in custom transformer
    StyleDictionary.registerTransform({
      name: 'my-custom-transform',
      filter: isSourceFilter, // ← imported filter function
      transform: (token) => // ...
    });
  4. Get started with style-dictionary-utils

    main

    The recommended way to use the utilities is to import the prepared StyleDictionary object from style-dictionary-utils instead of the standard style-dictionary package. This object comes pre-configured with the included filters, transformers, and formats.

    Note: If you are using Style Dictionary v4, you must await the .extend() method.

    // build.ts
    import {StyleDictionary} from 'style-dictionary-utils'
    
    const myStyleDictionary = new StyleDictionary()
    
    // when using style dictionary 4 you whave to await the extend method
    const extendedSd = await myStyleDictionary.extend({
      platforms: {
        ts: {
          transforms: ['color/css', 'shadow/css'],
          files: [
            {
              filter: 'isSource',
              destination: 'tokens.ts',
              format: 'javascript/esm',
            },
          ],
        },
      },
    })
    
    extendedSd.buildAllPlatforms()
  5. Configure the css/advanced format

    main

    The css/advanced format exports a token dictionary as a CSS file using CSS variables. It supports advanced features like media queries and custom selectors.

    Key Options:

    • selector: A string wrapped around your CSS. Defaults to :root. Set to false to disable the selector.
    • rules: An array of rule objects used to wrap specific tokens in CSS blocks (like @media queries or specific attribute selectors).

    Rule Object Properties:

    • atRule: A string or array of strings (e.g., @media (min-width: 768px)) that wraps the CSS.
    • selector: A string that wraps the CSS inside the atRule. If undefined, it falls back to the global file.options.selector.
    • matcher: A filter function (token: StyleDictionary.TransformedToken) => boolean. Only tokens returning true will be included in that specific rule.
    myStyleDictionary.extend({
      "platforms": {
        "css": {
          "transforms": //...,
          "files": [{
            // ...
            "format": "css/advanced",
            "options": {
              selector: `body[theme="dark"]`,
              rules: [
              {
                atRule: '@media (min-width: 768px)',
                selector: `body[size="medium"]`,
                matcher: (token: StyleDictionary.TransformedToken) => token.filePath.includes('tablet')
              }]
            }
          }]
        }
      }
    });
  6. Use getHasAttribute to filter by property existence

    main

    The getHasAttribute function returns a filter function that checks if a token has at least one of the specified properties.

    You can use it in two ways:

    1. Register it as a new filter: Use StyleDictionary.registerFilter to give it a name for use in configuration strings.
    2. Use it directly in a platform: Pass the function returned by getHasAttribute directly into the filter key of a file configuration.

    Signature: getHasAttribute(...properties: string[])

    // Register as a new filter
    import StyleDictionary from 'style-dictionary-utils'
    import {getHasAttribute} from 'style-dictionary-utils/filter/getHasAttribute.js'
    
    StyleDictionary.registerFilter({
      name: 'shouldAvoid',
      matcher: getHasAttribute('deprecated', 'removed'),
    })
    
    // Use directly in platform
    import StyleDictionary from 'style-dictionary-utils'
    import {getHasAttribute} from 'style-dictionary-utils/filter/getHasAttribute.js'
    
    myStyleDictionary.extend({
      "platforms": {
        "deprecatedJson": {
          "transforms": //...,
          "files": [{
            "filter": getHasAttribute('deprecated','removed'),
            // ...
          }]
        }
      }
    });
  7. Use getHasAttributeValue to filter by property value

    main

    The getHasAttributeValue function returns a filter function that checks if a token has specific properties with specific values.

    • If you provide an array of values for the second argument, every property checked can have any of those values.
    • You can use it by registering it as a named filter or by using the function directly in a platform configuration.

    Signature: getHasAttributeValue(attributes: string[], values: any[])

    // Register as a new filter
    import StyleDictionary from 'style-dictionary-utils'
    import {getHasAttributeValue} from 'style-dictionary-utils/filter/getHasAttributeValue.js'
    
    StyleDictionary.registerFilter({
      name: 'isDeprecated',
      matcher: getHasAttributeValue('deprecated', true),
    })
    
    // Use directly in platform
    import StyleDictionary from 'style-dictionary-utils'
    import {getHasAttributeValue} from 'style-dictionary-utils/filter/getHasAttributeValue.js'
    
    myStyleDictionary.extend({
      "platforms": {
        "deprecatedJson": {
          "transforms": //...,
          "files": [{
            "filter": getHasAttributeValue('deprecated',true),
            // ...
          }]
        }
      }
    });
  8. Register a Transform Group

    main

    If you need to reuse a specific set of transformers multiple times, you can register a transform group using registerTransformGroup. This allows you to refer to the group by name in your platform configuration.

    myStyleDictionary.registerTransformGroup({
      name: 'webHex',
      transforms: ['color/css', 'dimension/css', 'typography/css'],
    })
  9. Use getIsType to filter by $type

    main

    The getIsType function returns a filter function that filters tokens based on their $type property. You can provide one or multiple types to match against.

    Signature: getIsType(...types: string[])

    Usage patterns:

    • Register as a new filter: Use StyleDictionary.registerFilter to create a named filter (e.g., isAnimation) that matches multiple types like duration, transition, and cubicBezier.
    • Use directly in platform: Pass the function directly to the filter key in your platform configuration to allow specific types (e.g., size or dimension).
    // Register as a new filter
    import StyleDictionary from 'style-dictionary-utils'
    import {getIsType} from 'style-dictionary-utils/filter/getIsType.js'
    
    StyleDictionary.registerFilter({
      name: 'isAnimation',
      matcher: getIsType('duration', 'transition', 'cubicBezier'),
    })
    
    // Use directly in platform
    import StyleDictionary from 'style-dictionary-utils'
    import {getIsType} from 'style-dictionary-utils/filter/getIsType.js'
    
    myStyleDictionary.extend({
      "platforms": {
        "ts": {
          "transforms": //...,
          "files": [{
            "filter": getIsType('size','dimension'),
            // ...
          }]
        }
      }
    });
  10. Configure color output formats for `w3c-color/css`

    main

    You can control the resulting CSS color string format by setting the colorOutputFormat key in your platform configuration. If not provided, it defaults to 'hex'.

    Supported colorOutputFormat values:

    • 'hex': Hexadecimal color string (default).
    • 'rgb' or 'rgba': rgba(r, g, b, a) format using 0-255 integer values.
    • 'rgbFloat': An object containing {r, g, b, a} with floating point values.
    • 'hsl' or 'hsla': hsl(hdeg s% l% / a) format.

    Note: The transformer also maps specific color space names to CSS-compatible identifiers:

    • display-p3 $\rightarrow$ p3
    • a98-rgb $\rightarrow$ a98rgb
    • prophoto-rgb $\rightarrow$ prophoto
    {
      "platforms": {
        "css": {
          "colorOutputFormat": "rgba"
        }
      }
    }
  11. Use the typescript/esm-declarations format

    main

    The typescript/esm-declarations format exports a token dictionary as a TypeScript declaration file (.d.ts).

    // Output example
    export default {
      colors: {
        primary: string,
      },
    }
    
    // Usage in config
    myStyleDictionary.extend({
      "platforms": {
        "ts": {
          "transforms": //...,
          "files": [{
            "format": "typescript/esm-declarations",
          }]
        }
      }
    });