webpack-contrib/sass-loader

Variables

badsyntax opened this issue · 4 comments

Hi there

I am facing a problem with sharing sass variables across different require() calls. I am appending values to a list variable and I need that variable to be shared between different SCSS modules.

A real world scenario is attempting to a "import-once" function that prevent CSS from being output more than once:

// _functions.scss
$imported-once-files: () !default;

@warn $imported-once-files; // debug

@function import-once($filename) {
  @if index($imported-once-files, $filename) {
    @return false;
  }
  $imported-once-files: append($imported-once-files, $filename) !global;
  @return true;
}

You cannot use such an approach with sass-loader as each require() call is completely contained from other require() calls, thus $imported-once-files is reset with each require() call. I think the only way to resolve this issue to load all component files with sass and have only one entry point require('app.scss') call.
I'm hoping I'm making sense! Do you have suggestions on how I could make variables global across different require() calls?
Thanks!

jhnns commented

Yep, that's a known problem of preprocessors (both SASS and Less). I haven't found an easy way for SASS, though. Less introduced the import (reference) mechanism for that use-case.

@badsyntax if all you need are shared variables, why not have all of them in a file with only variables, that way it doesn't matter if it's imported multiple times? Like this:
https://github.com/twbs/bootstrap/blob/v4-dev/scss/_variables.scss

jhnns commented

We can't solve this because each require() of a SASS file from a JS file will trigger a distinct compilation. This is how loaders work.