How to throw an error in the LESS compiler

503 views Asked by At

Question

Is there any way to (programmatically) throw an error in the LESS compiler?

Why?

I have been fiddling around with mixin guards today, because I wanted to generate my CSS margin based upon element size and element count. I thought it would be cool to directly throw an error on compilation, when the elements won't fit in the wrapper.

Info: I am using the lessc compiler to compile my LESS code to CSS. I am not using any Javascript library to compile it on execution time.

LESS source

// Variables
@wrapper-small:  830px;
@wrapper-big:   1200px;

.col-fixed(@size, @count, @wrapper)  when ((@size*@count) <= @wrapper)
{
    width: unit(@size, px);
    margin-right: unit( (@wrapper - @count * @size) / (@count - 1), px);    
}

.test_col_fixed {
    // will fail the mixin guard and output no generated CSS        
    .col-fixed(340, 3, @wrapper-small);

    // would work if not in comment
    // .col-fixed(340, 3, @wrapper-big);
}

Generated CSS (small wrapper)

No output, because the code will not be generated due to the not matching mixin guard when ((@size*@count) <= @wrapper) // 3*340 <= 830 is false.

Generated CSS (with working solution, big wrapper)

.test_col_fixed {
    width: 340px;
    margin-right: 90px;
}
1

There are 1 answers

1
Smamatti On BEST ANSWER

Suggested, but strictly not recommended solution by Harry

.col-fixed(@size, @count, @wrapper) {
    & when ((@size*@count) <= @wrapper) {
        width: unit(@size, px);
        margin-right: unit( (@wrapper - @count * @size) / (@count - 1), px);  
    }
    & when ((@size*@count) > @wrapper) {
        /* there is no such variable and hence when the input value is not valid,
        compiler will complain that variable is undefined */
        output: @bwahahaha;
    }
}