4

tl;dr: Is there any way to share a set of global variables across multiple files without manually importing them into every file and without using the @import rule?


I used to use @import in a central index.scss file to make some variables available to all other modules imported below also in that file.

Like this:

index.scss

@import "variables";
@import "cards";
@import "buttons";

_variables.scss

$primaryColor: lightgreen;
$accentColor: deepskyblue;

_cards.scss

.card {
  background-color: $primaryColor;
}

_buttons.scss

.cta {
  border-color: $accentColor;
}

Referring to variables like $primaryColor in a module different from where the variable had originally been defined worked, and I didn't have to import the _variables.scss file everywhere I need to have them available.

Using @use

Since the announcement of the deprecation of the @import rule, I've been trying to migrate to the @use rule. But, the setup I had no longer works.

I've tried modifying my index file like this:

index.scss

@use "variables" as *;
@use "cards";
@use "buttons";

But, referencing a variable like $accentColor inside the _cards.scss module, for instance, no longer works.

The only way I've found to make this work so far is to manually import the _variables.scss file with @use into every module where I access those global variables. However, this is cumbersome and I'd like to avoid it.

Is there any way to share a set of global variables across multiple files without manually importing them into every file and without using the @import rule?

Thank you so much in advance for any help.

M2K
  • 319
  • 3
  • 11

1 Answers1

2

@import@use "variables" in your main style sheet file application.scss. See answer

zswqa
  • 826
  • 5
  • 15