lessless-mixins

Mark a Less mixin as optional


Less lets you mark an import as optional like this:

@import (optional) "foo.less";

I have a Less file that I'm importing optionally which contains a mixin that I use in the parent file.

How can I mark the usage of a mixin as optional, so rendering doesn't fail if my imported Less file doesn't exist?

I've tried this, planning on setting @styleguide in the optional Less imported file, but rendering fails regardless of the value of @styleguide when it realizes .registerColors() doesn't exist.

& when (@styleguide=true) {
    .registerColors( ... arguments ... );
}

I need the solution to work with Less 2.5.3.


Solution

  • Mixins in Less cascade, so you can simply define an empty mixin anywhere in a non-optional code section. E.g.:

    @import (optional) "some";
    
    div {
        .registerColors(red, red 2);  
    }
    
    // non-optional stuff
    
    .registerColors(...) {}
    

    Demo. When optional imports define a mixin of the same name, both mixin definitions are invoked.