Skip to content

Documentation suggestion: Import JSON objects (not from files) #101

@rootwork

Description

@rootwork

I wasn't entirely sure if I could use JSON objects that already existed in my code without having to save them to a file first. Using the Importing *.js Files documentation I was able to do it, but I thought it might be worth adding documentation that makes that explicit.

I can create a PR for this if you agree. Here's the basic version:


  1. Provide an object of JSON values. You can do this directly like so:
const theme = {
  "colors": {
    "primary": "#900",
    "secondary": "#060"
  }
}

or you can use JSON.stringify to transform any objects you already have into JSON-formatted objects.

  1. If you have nested objects, it appears that you can't access them through Sass's map-get() function. So with the above example data, you couldn't do color: map-get($theme.colors, 'primary'). Instead, you have to create objects of the nested objects, e.g.:
const colors = theme.colors
  1. Then, as in the "Importing *.js Files" example, export your objects:
module.exports = {
  colors
}
  1. Finally, call the JS file you've just created and use the map-get() function:
@import 'theme.js';

a {
  color: map-get($colors, 'primary');
}

My particular use case was providing a way for people to define theme components in a YAML file, then using js-yaml to read them in. So it seemed really silly to then have to export the settings back to a JSON file just for consumption by the JSON importer! Doing it with the objects alone made me much happier.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions