Thomas Parfitt
Thomas Parfitt

Reputation: 43

Cannot make variables globally accessible in SASS

I'm trying to set global variables in one file and then use these variables in all other scss files throughout the application. When I set the variables I can use them in that specific file but not others. I am using the '@use' method instead of '@import' as the sass docs recommended it however it seems the '@import' method would achieve what I need however I need a workaround for the long term. Finally, I tried using the '@forward' method but could not see any change and I got the same errors.

app.scss

@use 'layouts/variables.scss';
@use 'layouts/forms.scss';

_variables.scss

$ds-black: #212121;

_forms.scss

input
{
    border: 1px solid $ds-black;
}

Console output when compiling:

Error: Undefined variable.
   ╷
14 │     border: 1px solid $ds-black;
   │                       ^^^^^^^^^
   ╵
  resources\css\layouts\_forms.scss 14:23  @use
  resources\css\app.scss 4:1               root stylesheet

I tried using the ' !global ' attribute however I got this error as well as the previous

Deprecation Warning: As of Dart Sass 2.0.0, !global assignments won't be able to
declare new variables. Since this assignment is at the root of the stylesheet,
the !global flag is unnecessary and can safely be removed.

  ╷
9 │ $ds-black: #212121 !global;
  │ ^^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵
    resources\css\layouts\_variables.scss 9:1  @use
    resources\css\app.scss 3:1                 root stylesheet

Upvotes: 0

Views: 4028

Answers (2)

bowrilla
bowrilla

Reputation: 184

If you want to use the new Sass module system and have stylesheets that are only used as modules and should not be compiled on their own, you should name your mopules with a leading "_" so the compiler knows to treat them as partials. You then have those two options, Kenyi Larcher showed you.

Upvotes: 0

Kenyi Larcher
Kenyi Larcher

Reputation: 292

https://sass-lang.com/documentation/at-rules/use#choosing-a-namespace

You could change the use tag to something like

@use 'layouts/variables' as *;

or

@use 'layouts/variables';

//and then
input
{
    border: 1px solid variables.$ds-black;
}

Upvotes: 2

Related Questions