3

I've been using what I thought was a very elegant pattern for defining the styles of reusable components/widgets, using LESS. It works beautifully in LESS 1.3-, but after upgrading recently, my whole library is broken. Does anyone know a way to accomplish something like this in 1.4+?

Here's a very simple example of a component:

#componentName {
  .loadMixins(){
    .text() {}
    .header() {}
  }

  .apply(){
    > h3 {
      // markup-specific styles
      padding: 3px;
      margin-bottom: 0;

      // custom styles
      .header();
    }

    > div.body, > div.popup p {
      color: red;

      // custom styles
      .text()
    }
  }
}

And here's how it would be used:

.coolWidget {
  #componentName.loadMixins();

  // override mixins here
  .text(){
    color: green;
  }

  #componentName.apply();
}

This keeps all the markup-dependent styles abstracted from the user. I could completely change my markup and the user's styles would still work. According to the less.js changelog, 1.4.0 Beta 1 has a line "variables in mixins no longer 'leak' into their calling scope"

Is there any way around this?

1 Answer 1

1

Strictly speaking nested variables and mixins are still expanded into calling scope unless this scope already has those names defined.

Your example above results in a error:

SyntaxError: .header is undefined...

and it's expected as no .header() is actually defined within the .coolWidget (or anywhere else). This can be fixed by providing "default" definitions for .text and .header somewhere inside #componentName. For example if you modify .loadMixins() to:

.loadMixins() {
    .text();
    .header();

    // default properties in case a caller does not provide its own:
    .text()   {}
    .header() {}
}

then the example compiles OK and all text/header properties are overridden as expected.


I can imagine how your library may become broken because of new scope rules but this particular example you gave above does not illustrate the problem.

3
  • Hi Max! Thanks so much for the answer – you are right, I mistyped my example – the .loadMixins() mixin is supposed to set defaults. Just made an example codepen.io/anon/pen/wGyHb and it looks like they use 1.3.x so overrides are working. If you run it in 1.4.x, though, no dice :( I'd love to find another way to do this. Sep 16, 2013 at 5:30
  • Of course my answer above is about 1.4.x (I tested with lescc 1.4.2 and 1.5.0-b2) where this code still works (and there's no reason why it should not). Sep 16, 2013 at 21:23
  • You, sir, are totally right – I just ran this in a different environment and it worked. Looks like I have an environment-specific problem. Thanks so much for the help and for all your time! Sep 17, 2013 at 3:53

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.