question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Config.js with json properties

See original GitHub issue

Hello,

I’m following this example: https://github.com/amzn/style-dictionary/blob/main/examples/advanced/node-modules-as-config-and-properties/config.js

And I want to convert all my colors to XCode colorsets, hence for this I need to convert each color to separate file, which is there in example:

      files: Object.keys(properties.color).map((colorType) => ({
        destination: `${colorType}.js`,
        format: 'javascript/es6',
        // Filters can be functions that return a boolean
        filter: (prop) => prop.attributes.type === colorType
      }))

But there is issue with properties variable:

const properties = require('./properties');

This code does import all properties in .js format, but I can’t change properties and having simple json files as here https://github.com/amzn/style-dictionary/tree/main/examples/basic/properties. How to get this const properties from json files.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
dbanksdesigncommented, Nov 30, 2020

I made a quick example project to answer this question: https://github.com/dbanksdesign/style-dictionary-example-colorsets

The example answers 2 questions:

  1. How to combine JSON files outside of Style Dictionary to use the object to create files in the Style Dictionary configuration. However I don’t think that is the best way to create iOS colorsets because a colorset is a single color and it would be hard to create an array of all the colors without using the dictionary.allProperties in a custom action.
  2. How to create iOS colorsets using a custom action. This is how I create colorsets my projects, but if others have other ways to do this I would love to see them!

Posting the code here (note this might not match the example if I update the example in the future):

const combineJSON = require('style-dictionary/lib/utils/combineJSON');
const fs = require('fs-extra');
const glob = require('glob');
const Color = require('tinycolor2');

// Use style dictionary's internal method for combining JSON files
// to get a properties object
const properties = combineJSON([`tokens/**/*.json`], true);

// The directory to build the colorsets in
const assetsDir = 'build/ios/Assets.xcassets';

// Custom action for creating iOS colorsets
const createColorsets = (dictionary) => {
  dictionary.allProperties
    // grab all colors
    .filter(token => token.attributes.category === 'color')
    .forEach(token => {
      const folder = `${assetsDir}/${token.name}.colorset`;
      const file = `${folder}/Contents.json`;
      const contents = {
        colors: [
          {
            'color-space': "srgb",
            idiom: "universal",
            components: {
              alpha: `${token.value.a}`,
              red: `${token.value.r}`,
              green: `${token.value.g}`,
              blue: `${token.value.b}`,
            }
          }
        ]
      };
      // create the directory if it doesn't exist
      fs.ensureDirSync(folder);
      // create the Contents.json file
      fs.writeFileSync(file, JSON.stringify(contents, null, 2));
    });
}

// Exporting an object as the style dictionary configuration
// see 'build' npm script in package.json for how this is used
module.exports = {
  // Directly adding custom actions on the configuration
  // You could also do: StyleDictionary.registerAction() as well
  action: {
    createColorsets: {
      do: createColorsets,
      undo: function(dictionary, config) {
        // clean up colorsets we build when the package is cleaned
        glob(`${assetsDir}/*.colorset`, function (error, results) {
          results.forEach((colorsetFolder) => {
            fs.removeSync(colorsetFolder);
          });
        });
      }
    },
  },
  
  // Same with custom transforms, I just like doing it this way
  transform: {
    colorRGB: {
      type: `value`,
      matcher: (token) => token.attributes.category === 'color',
      transformer: (token) => {
        return Color(token.value).toRgb();
      }
    }
  },
  
  // Adding the properties object here directly rather than using `source`
  properties: properties,
  
  platforms: {
    js: {
      transformGroup: 'js',
      buildPath: `build/web/`,
      // Now you can access the properties object to build files based on
      // its structure
      files: Object.keys(properties.color).map((colorType) => ({
        destination: `${colorType}.js`,
        format: `javascript/es6`,
        filter: (token) => token.attributes.type === colorType
      }))
    },
    iOSColors: {
      transforms: [`attribute/cti`,`colorRGB`,`name/cti/pascal`],
      // Using our custom action to build colorsets
      actions: [`createColorsets`]
    }
  }
}

Hopefully that answers your questions, if not let me know!

2reactions
kellettemmacommented, Feb 12, 2021

Awesome @dbanksdesign, works a charm - thanks so much 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Advanced JSON configuration properties
You can use a JSON configuration file to define certain properties for individual tenants, rather than configuring environment variables ...
Read more >
jsconfig.json Reference - Visual Studio Code
The jsconfig. json file specifies the root files and the options for the features provided by the JavaScript language service.
Read more >
Configuring properties from config.json using services. ...
You can access specific value in config.json like: Configuration.Get("SomeOptions:MyOption ...
Read more >
Configuration with app.json / app.config.js
Properties. The Expo config configures many things such as app name, icon, splash screen, deep linking scheme ...
Read more >
JSON-based Config
Chart, or any of its descendant elements, are basically a JavaScript object. Objects can have methods and properties. Methods (or functions) cannot be ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found