6

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

It's not working, its only get "undefined variable" error.
0

Unfortunately, you can't do this anymore:

To be clear: we're not going back to globally-visible names. That was one of the biggest design flaws of the import system, and it's totally incompatible with the module system's goal of making it clear where each name comes from in a given file and thus with making it easy to read and comprehend Sass. It's our fault for introducing global names in the first place and letting it metastasize so broadly into the ecosystem, and we apologize for that. We'll do everything we can to help people transition gracefully and learn how to work with the new way of doing things.

https://github.com/sass/sass/issues/2750#issuecomment-1498338102

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.