Search code examples
reactjssassnode-sass

SassError: Undefined variable, Failed to Compile but compile seems to work


I'm using node-sass in my react project. I have setup a index.scss that contains imports for my variables, mixins and all of my components. The index.scss is set to compile to index.css.

Now, I have a file called _variables.scss that I'm importing at the top of my index.scss:

// index.scss

@import "styles/variables";
@import "components/Button/Button";

In my Button.scss I'm setting color: $red_hero; and getting this error in my console:

Compiled src/index.scss to src/index.css.
Compiling...
Failed to compile.


SassError: Undefined variable: "$red-hero".

What's weird for me is that it used to work but now it doesn't anymore. What's even weirder is that the compiled index.css is rendering correctly, but the page refuses to render:

// index.css

.Button {
  color: #A33343;
}

My guess is that it's an internal problem with sass and that the webpage isn't loading the index.css like it should. I've also noticed other strange behavior where a webpage is loading styling from a components scss-file even when I've neglected to import that component into my index.scss.

Any help or ideas would be greatly appreciated.


Solution

  • Solved!

    After much more time spent problem solving than I care to admit, I narrowed the problem down to only happening when using the package generate-react-cli. An autogenerated component has a line at the top of the .js-file that imports it's scss file.

    My setup is dependant on manually importing each components scss file into one root scss file that can be compiled to one regular css file, where placing imports to files with variables at the top of the index.scss makes those variables accessible to all other scss files. When a single component imports it's own scss-file with a variable in it the compiler doesn't know how to evaluate it, and thus it crashes.

    Solution, don't import scss files from anywhere else but the main .scss-file.