0

I'm looking for the best way to avoid globally diffused variables.

I made a test with this configuration:

_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";

The output with lessc index.less test.css still looks like

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

But what I'm looking for is:

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

Using less 2.7 or 3.9 give the same behavior.
Do someone know a solution?
Thanks

1
  • This is by design: When defining a variable twice, the last definition of the variable is used, searching from the current scope upwards. ref If you want to avoid it, use a different variable, or import your files dynamically (based on a condition) Commented Feb 21, 2019 at 15:46

1 Answer 1

2

You can always isolate the scope of anything (incl. an imported file) using "unnamed namespace", i.e. & {}, block.

E.g.:

test.less:

@import "_import";

body {
    background: @test;
}

test2.less:

@import "_import2";

div {
    background: @test;
}

index.less:

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

Depending on your goals these & {} blocks can be moved right into the test files themselves.

---

Ref: Local Variable Scoping in Import Files

Sign up to request clarification or add additional context in comments.

3 Comments

this is interesting. didn't know about this. What would be an example of a good reason to use this? I find that the OP wouldn't even benefit, because why import it at all if your going to scope it out?
@soulshined I guess a typical use case is to merge unrelated libraries/components (using same variable names) into one. And/or something like this.
Just thanks, it's awesome. Doc should be improved because there's no way to find is easily

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.