sass / dart-sass

The reference implementation of Sass, written in Dart.
https://sass-lang.com/dart-sass
MIT License
3.9k stars 352 forks source link

How to prevent global variable re-defined when imported more than once? #2299

Closed aztack closed 1 month ago

aztack commented 1 month ago

I'm trying to prevent a global variable from being re-defined (returning to the initial value) by testing its existence with global-variable-exists function and initializing it only if it doesn't exist (the first time imported):

global.scss:

@use "sass:meta";
@use "sass:map";
@if not global-variable-exists(global) {
    $global: null !global;
}
@if $global == null {
    $global: (default: (user: (name: "a", age: 2)));
} @else {
    @debug("global already initialized");
}

a.scss:

@use "sass:map";
@import './global.scss';

$global: map.deep-merge($global, (default: (user: ("name": 'aa', "age": 33))));
@debug($global);

@import './global.scss';
@debug($global);

Here is the output of running sass a.scss:

Deprecation Warning: As of Dart Sass 2.0.0, !global assignments won't be able to declare new variables.

Recommendation: add `$global: null` at the stylesheet root.

  ╷
4 │     $global: null !global;
  │     ^^^^^^^^^^^^^^^^^^^^^
  ╵
    global.scss 4:2  @import
    a.scss 2:9       root stylesheet

a.scss:5 Debug: (default: (user: (name: "aa", age: 33)))
global.scss:9 Debug: global already initialized
a.scss:8 Debug: (default: (user: (name: "aa", age: 33)))

But I got the deprecating warning above. If I add $global: null at the stylesheet root. $global will be set to null every time global.scss is imported and this makes the testing pointless.

Is there a recommended way to prevent a scss file from being imported multiple times?

Goodwine commented 1 month ago

This is one of the many reasons why we recommend against using @import. Prefer using @use instead. The documentation calls out these reasons: https://sass-lang.com/documentation/at-rules/import/

Specifically:

Each stylesheet is executed and its CSS emitted every time it’s @imported, which increases compilation time and produces bloated output.