Search code examples
sassruby-on-rails-6webpacker

Rails SCSS global variables


I've set up my project to use Bootstrap and scss with Webpacker, however, whenever I start my server locally I get this error:

ActionView::Template::Error (Error: Undefined variable: "$secondary-accent".
        on line 76:23 of app/assets/stylesheets/_hero.scss
>>   border: solid 0.5px $secondary-accent;

This error actually goes away locally if I do a hard refresh, but of course, Capistrano is not as forgiving and I want to figure out the issue anyway.

In my /app/javascscript/ folder I have a src/style.scss file which imports the required stylesheets.

@import '../../assets/stylesheets/_globals.scss'; //import globals first so the values propagate to Bootstrap
@import '~bootstrap/scss/bootstrap'; //import bootstrap
@import '../../assets/stylesheets/application.scss' //import everything else;

/assets/stylesheets/application.scss looks like:

@import '_navbar';
@import 'actiontext';
@import '_hero';
@import 'comments';
@import 'static_pages';

body {
  font-family: $body-font;
  font-size: $standard;
}

Of course, the easy way to get rid of this is to just add @import 'globals' to each of the partials but that does not seem to fit with the sass way. I don't really want to add @import 'globals' at the top of every single .scss file, not a big deal at the moment but as the project grows and the complexity of the styles increases maintainability could become a headache. I thought that Webpacker would take care of this, am I wrong? Am I missing something in the setup?

Ps. I realize this question has been asked dozens of times, but they all seem to be for older versions of Rails, or the solutions don't apply to me (such as removing the require tree from application.css


Solution

  • This was resolved by tightening my Webpacker set up a bit.

    The biggest issue was installing scss I thought sass-rails in my gemfile was sufficient but I also needed yarn add scss. I didn't need to import the globals inside of src/style.scss just in application.scss.