less css 避免全球化变量

less css avoid globalized variable

我正在寻找避免全局扩散变量的最佳方法。

我用这个配置做了测试:

_import.less

@test: #FFF;

_import2.less

@test: #000;

test.less

@import (reference) "_import";

body {
    background: @test;
}

test2.less

@import (reference) "_import2";

div {
    background: @test;
}

index.less

@import "test";
@import "test2";

带有 lessc index.less test.css 的输出仍然看起来像

body {
  background: #000;
}
div {
  background: #000;
}

但我要找的是:

body {
  background: #FFF;
}
div {
  background: #000;
}

使用较少的 2.7 或 3.9 会产生相同的行为。
有人知道解决方案吗?
谢谢

您始终可以使用“未命名的命名空间”来隔离任何内容(包括导入的文件)的范围,即 & {}、块。

例如:

test.less:

@import "_import";

body {
    background: @test;
}

test2.less:

@import "_import2";

div {
    background: @test;
}

index.less:

& {@import "test";}
& {@import "test2";}

根据您的目标,这些 & {} 块可以直接移动到 test 文件中。

---

参考:Local Variable Scoping in Import Files