BAR
BAR

Reputation: 17121

Loading SASS Variables in ES6

How does one use a SASS variable in an ES6 file?

import base from '../../../styles/_base.scss'

const styles = {
  cardHeader: {
    backgroundColor: base.neutralColorLight  // Does not work
  }
}

<CardHeader style={styles.cardHeader} />

The stylesheet:

// _base.scss

$neutral-color-light: rgb(232, 232, 232);

Upvotes: 1

Views: 1683

Answers (1)

Kyle Fahringer
Kyle Fahringer

Reputation: 294

Use node-sass-json-vars

The npm package node-sass-json-vars allows you to specify json files in @import. Since you can also import json files in javascript, this allows for easy usage between the two.

To use it, you'd install node-sass-json-importer with NPM and specify it as an importer on the command line:

./node_modules/.bin/node-sass --importer node_modules/node-sass-json-importer/dist/node-sass-json-importer.js MySASSFile.scss

In your sass file, you wouldn't specify the variables, instead leaving that to the json file:

@import 'colors.json'

.neutral-thing {
  color: $neutral-color-light
}

And you would do the following in the json file:

{
  "neutral-color-light": "rgb(232, 232, 232)"
}

And in your JS file, just import the json:

import colors from './colors.json'

const styles = {
  cardHeader: {
    backgroundColor: colors.neutral-color-light
  }
}

Upvotes: 3

Related Questions