4
votes

I have some color defined variables into _colors.scss file.

$color-succcess: #706caa;
$color-error: #dc3545;

I would like to also use them into some styled react components react-table into my js file.

I used the following article https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript as reference and many others like it but I cannot get it to work.

I export the colors from my scss file:

:export {
  colorSuccess: $color-succcess;
  colorError: $color-error;
}

and I import them into my js file:

import colors from "../../styles/_colors.scss";

but they are probably not loaded right.

How can I configure the create-react-app generated code to achieve the same thing as the guy in the article does with webpack.

3

3 Answers

4
votes

I have faced a similar issue, and it took me a bunch of tries to get the desired result. If you already have node-sass installed, try the following.

  1. First of all, try importing the main scss file without the underscore, i.e. instead of ../../styles/_colors.scss, try ../../styles/index.scss or whatewer your main file is.

  2. Secondly, keep track of the variable names. This code DID NOT work:

:export {
  $textBlack: $text-black;
}

while this one works perfectly

:export {
  textBlack: $text-black;
}

For some reason it does not like the dollar sign in the variable name, though it is a valid JS variable name. Your case should work fine

1
votes

Try to reproduce these steps:

1. Enable sass in CRA by installing node-sass.

npm i --save-dev node-sass

2. Create a sass file example.scss.

$hello: 'world';

:export {
  my-var: $hello;
}

3. Import the sass into your react component.

import React from 'react';
import Example from './example.scss';

export default () => Example.hello;
-1
votes

In order to load SCSS files in CRA you need to add node-sass as your dependency to package.json. I've tested it out and after adding it to clean CRA project and importing colors object (using :export, like in the code you provided) works as expected.