pglatz
pglatz

Reputation: 173

In sass, replacing @import with @use not expanding variables

I want to start using @use instead of @import, since @import is going to be deprecated. I have a partial:

// _test.scss
$color1: #ee00ee;

referenced by:

// demo.scss
@use test;
html {
  color: $color1;
}

If I comment out the html: $color1 line, I get no error. If I delete _test.scss I get a file not found error, so it seems the file is included.

But when everything is in place, I'm getting an undefined variable error. If I replace @use with @import, I get no error and the generated css has the expected color.

I'm on a Mac (big sur), using dart sass:

% dart --version
Dart SDK version: 2.9.3 (stable) (Tue Sep 8 11:21:00 2020 +0200) on "macos_x64"

The docs I've seen say that @use will replace @import, so I thought just changing to @use would be easy. Is there a step I'm missing?

Upvotes: 6

Views: 2887

Answers (2)

squarecandy
squarecandy

Reputation: 5107

This article by Vaibhav Mehta provides some very helpful info on this topic: https://mr-alien.medium.com/use-forward-in-sass-70b9cd44218b

To summarize:

  • The new namespacing concept of @use is helpful in a lot of situations, so if you can adopt it while upgrading, you should.
  • If your filenames are long you can end up with unwieldily stuff like colors_for_theme_blue.$highlight-color. In this case you can use the 'as' keyword: @use 'path/to/colors_for_theme_blue' as c; and then in your sass code below you can now use c.$highlight-color.
  • If you really don't want to use namespacing, you can use a wildcard: @use 'path/to/colors_for_theme_blue' as *; - now your old plain variables like $highlight-color should work again.

Upvotes: 1

Mr. Mediocre
Mr. Mediocre

Reputation: 114

It's a bit late, but as I understand it, @use treats the partial as modules, which more closely resembles the way JavaScript treats ES modules: In particular, the @use statement makes available a namespaced bit of external code, which changes the way you reference imported variables (and mixins and functions as well):

// demo.scss
@use test;
html {
  color: test.$color1;
}

Some documentation is found in the article about @use on the SASS docs, and this article explains dart-sass' namespacing in some detail.

Upvotes: 3

Related Questions