How to assign to a global variable in Sass?

前端 未结 2 797
梦毁少年i
梦毁少年i 2020-11-27 08:08

I run this Sass code:

$a: 1;
@if 2 + 2 == 4 {
    $a: 2;
}
@debug $a;

I expect to see 2. The output, however, is:

Line 5 D         


        
相关标签:
2条回答
  • 2020-11-27 08:39

    By trial-and-error, I found a solution: I have to add !global in the assignment.

    $a: 1;
    @if 2 + 2 == 4 {
        $a: 2 !global;
    }
    @debug $a;
    
    0 讨论(0)
  • 2020-11-27 08:55

    As you're using Sass 3.4+, you should append the !global flag to your variable declaration:

    $a: 1;
    @if 2 + 2 == 4 {
        $a: 2 !global;
    }
    @debug $a; // will output 2
    

    The original SASS_REFERENCE on variable declaration stated:

    "Variables are only available within the level of nested selectors where they're defined. If they're defined outside of any nested selectors, they're available everywhere.

    but the SASS_CHANGELOG of 3.4+ shows that this behaviour has changed:

    All variable assignments not at the top level of the document are now local by default. If there’s a global variable with the same name, it won’t be overwritten unless the !global flag is used.

    For example, $var: value !global will assign to $var globally. This behavior can be detected using feature-exists(global-variable-shadowing).

    0 讨论(0)
提交回复
热议问题