Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

node-sass-json-importer

Updater102.3kMIT4.3.0

Allows importing json in sass files parsed by node-sass.

sass, node-sass, importer, json

readme

node-sass-json-importer

JSON importer for node-sass. Allows @importing .json or .json5 files in Sass files parsed by node-sass.

npm build status

Usage

node-sass

This module hooks into node-sass's importer api.

var sass = require('node-sass');
var jsonImporter = require('node-sass-json-importer');

// Example 1
sass.render({
  file: scss_filename,
  importer: jsonImporter(),
  [, options..]
}, function(err, result) { /*...*/ });

// Example 2
var result = sass.renderSync({
  data: scss_content
  importer: [jsonImporter(), someOtherImporter]
  [, options..]
});

node-sass command-line interface

To run this using node-sass CLI, point --importer to your installed json importer, for example:

./node_modules/.bin/node-sass --importer node_modules/node-sass-json-importer/dist/cli.js --recursive ./src --output ./dist

Webpack / sass-loader

Webpack v1

import jsonImporter from 'node-sass-json-importer';

// Webpack config
export default {
  module: {
    loaders: [{
      test: /\.scss$/,
      loaders: ["style", "css", "sass"]
    }],
  },
  // Apply the JSON importer via sass-loader's options.
  sassLoader: {
    importer: jsonImporter()
  }
};

Webpack v2

import jsonImporter from 'node-sass-json-importer';

// Webpack config
export default {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            },
          },
          {
            loader: 'sass-loader',
            // Apply the JSON importer via sass-loader's options.
            options: {
              importer: jsonImporter(),
            },
          },
        },
      ],
    ],
  },
};

Importing

Importing strings

Since JSON doesn't map directly to SASS's data types, a common source of confusion is how to handle strings. While SASS allows strings to be both quoted and unquoted, strings containing spaces, commas and/or other special characters have to be wrapped in quotes. In terms of JSON, this means the string has to be double quoted:

Incorrect
{
  "description": "A sentence with spaces."
}
Correct
{
  "description": "'A sentence with spaces.'"
}

See discussion here for more:

https://github.com/Updater/node-sass-json-importer/pull/5

Importing *.js Files

You can also import *.js Files. This way you can use javascript to compose and export json structure for node-sass-json-importer.

const xl = require('./variables.json')
const md = require('./variables-md.json')
const xs = require('./variables-xs.json')

module.exports = {
    xl,
    md,
    xs,
}

Custom resolver

Should you care to resolve paths, say, starting with ~/ relative to project root or some other arbitrary directory, you can do it as follows:

1.sass:

@import '~/1.json'
body
    margin: $body-margin

json/1.json:

{"body-margin": 0}
var path = require('path');
var sass = require('node-sass');
var jsonImporter = require('../dist/node-sass-json-importer');

sass.render({
  file: './1.sass',
  importer: jsonImporter({
    resolver: function(dir, url) {
      return url.startsWith('~/')
        ? path.resolve(dir, 'json', url.substr(2))
        : path.resolve(dir, url);
    },
  }),
}, function(err, result) { console.log(err || result.css.toString()) });

camelCase to kebab-case

If you want to convert standard JavaScript caseCase keys into CSS/SCSS compliant kebab-case keys, for example:

variables.json:

{
  "bgBackgroundColor": 'red'
}

For usage like this:

style.scss:

@import "variables.json";

div {
  background: $bg-background-color;
}

You can pass set the convertCase option to true as an argument to jsonImporter like so:

sass.render({
  file: './1.sass',
  importer: jsonImporter({
    convertCase: true,
  }),
}, function(err, result) { console.log(err || result.css.toString()) });

Thanks to

This module is based on the sass-json-vars gem, which unfortunately isn't compatible with node-sass.

changelog

Changelog

Deprecated

For versions above 4.1.0, please refer to "Releases" in GitHub UI.

4.1.0

4.0.1

  • Update package.json's main field (#73).

4.0.0

  • Add resolver option (ability to override how json file paths gets resolved) (#71).

    BBREAKING CHANGE:

    The importer is now a function, accepting an options object, instead of an object: jsonImporter -> jsonImporter()

3.3.1

  • Remove support for one element lists. 3.3.0 broke parsing of empty lists (#67).

3.3.0

  • Add support for one element lists.

    Comma-separated lists may have a trailing comma. This is especially useful because it allows you to represent a single-element list. For example, (1,) is a list containing 1 and (1 2 3,) is a comma-separated list containing a space-separated list containing 1, 2, and 3.

    https://sass-lang.com/documentation/file.SASS_REFERENCE.html#lists

3.2.0

  • Allow importing JSON as a top-level array.

3.1.6

  • Filter out # as value for a variable

3.1.5

  • Reverts 3.1.4. We aren't able to find a way to support automatic handling of values containing , that isn't full of edge cases. The recommendation remains to wrap such values in single quotes if they're meant to be interpreted as strings.

3.1.4

  • Convert values containing commas inside of an object into strings

3.1.3

  • Extend key filtering to nested maps

3.1.2

  • Filter out invalid variable names to prevent Sass compiler from crashing

3.1.1

  • Return empty strings correctly to prevent Sass compiler from crashing

3.1.0

  • Add support for .json5 files

3.0.2

Fixes
  • Fix includePaths option for Windows users by using the environment's delimiter instead of harcoding unix's.

3.0.1

Fixes
  • Update node-sass dependency versions from ^3.5.3 to >=3.5.3 to allow using 4.x and above without triggering npm warnings.
  • Add yarn.lock.

3.0.0

(Possibly) Breaking

2.1.1

Fixes
  • Fix 2.1.0 breaking the default export for CommonJS.

2.1.0

Features
  • Export internal methods that compose the importer. E.g. transformJSONtoSass can now be used independently of node-sass to transform parsed JSON into Sass.

2.0.0

Breaking
  • Add node-sass ^3.5.3 as a peerDependency.
Fixes

1.0.6

Fixes
  • Invalidate require cache on each importer run.

1.0.5

Fixes

1.0.4

Fixes
  • Revert attempting to wrap strings with spaces/commas (wrap strings in extra quotes instead).

1.0.3

Fixes
  • Fix importing strings with spaces/commas breaking. Reverted in 1.0.4

1.0.2

Fixes
  • Fix includePaths not working with multiple entries.