少css避免全球变量

问题描述 投票:0回答:1

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

我用这个配置做了一个测试:

_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会产生相同的行为。 有人知道解决方案吗? 谢谢

css less
1个回答
2
投票

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

例如:

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

© www.soinside.com 2019 - 2024. All rights reserved.