You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:15:57