/node-sass-json-importer

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

Primary LanguageJavaScriptMIT LicenseMIT

node-sass-json-importer build status

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

Usage

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/node-sass-json-importer.js --recursive ./src --output ./dist

Webpack / sass-loader

Webpack v1 or below v2.1.0-beta.23

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

// Webpack config
export default {
  module: {
    // Example sass-loader usage. 
    // See: https://github.com/jtangelder/sass-loader#apply-via-webpack-config
    loaders: [{
      test: /\.scss$/,
      loaders: ["style", "css", "sass"]
    }],
  },
  sassLoader: {
    // Apply the JSON importer via sass-loader's options.
    importer: jsonImporter
  }
};

Webpack v2.1.0-beta.23 or above

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

// Webpack config
export default {
  module: {
    // Example sass-loader usage. 
    // See: https://github.com/jtangelder/sass-loader#apply-via-webpack-config
    loaders: [{
      test: /\.scss$/,
      loaders: ["style", "css", "sass"]
    }],
  },
  plugins: [
    // ...other plugins
    
    new webpack.LoaderOptionsPlugin({
      options: {
        sassLoader: {
          importer: jsonImporter,
        },
        context: __dirname,
      },
    }),
  ]
};

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 unqouted, 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:

pmowrer#5

Thanks to

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