SASS与LESS变量指向行为差异及SASS变量覆写方案咨询
Great question! Let's break this down clearly. First, let's restate the code scenario to make sure we're on the same page:
Original Code Snippet
SASS Version (compiles to $lol: blue)
// Bootstrap library code (can't modify these lines) $lil: blue; $lol: $lil; // Your override attempt $lil: red;
LESS Version (compiles to @lol: red)
// Bootstrap library code @lil: blue; @lol: @lil; // Your override @lil: red;
The key difference here is that LESS uses lazy variable evaluation (variables are resolved when used, not when defined), while Sass uses immediate evaluation (variables are assigned their value right when they're declared). That's why your $lil: red override doesn't affect $lol in Sass—it already locked in the initial blue value when $lol: $lil ran.
Solution 1: Modify $lol to Use a Dynamic Function
To make $lol automatically reflect the overridden $lil value in Sass, we need to change how $lol retrieves its value. Instead of assigning it a static initial value, we'll have it reference a function that returns the current value of $lil whenever $lol is used.
Here's the adjusted $lol definition (this is the only modification needed to the variable itself):
// Modified Bootstrap $lol line $lol: get-current-lil(); // Bootstrap's original $lil definition (unchanged) $lil: blue; // Add this function in your custom code (no Bootstrap core edits needed) @function get-current-lil() { @return $lil; } // Your override (unchanged) $lil: red;
Now whenever $lol is used, it calls the function to fetch the latest value of $lil—which will be red after your override—matching LESS's behavior.
Solution 2: Reassign $lol After Overriding $lil
If adding a function isn't an option, a simpler (though more explicit) fix is to reassign $lol directly after your $lil override. This counts as modifying the $lol variable to pick up the updated value:
// Bootstrap code (unchanged) $lil: blue; $lol: $lil; // Your code $lil: red; $lol: $lil; // Reassign $lol to the new $lil value
This works by explicitly updating $lol to reference the overridden $lil value, bypassing Sass's immediate evaluation behavior.
内容的提问来源于stack exchange,提问作者Jonathan de M.

