如何在 LESS 编译器中抛出错误

Sma*_*tti 5 css compiler-errors throw less less-mixins

问题

有什么方法可以(以编程方式)在 LESS 编译器中抛出错误吗?

为什么?

我今天一直在摆弄 mixin 防护,因为我想根据元素大小和元素计数生成 CSS 边距。我认为当元素不适合包装器时,直接在编译时抛出错误会很酷。

信息:我正在使用lessc编译器将 LESS 代码编译为 CSS。我没有使用任何 Javascript 库在执行时编译它。

更少的来源

// 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);
}
Run Code Online (Sandbox Code Playgroud)

生成的 CSS(小包装)

没有输出,因为由于 mixinguard 不匹配,代码不会生成when ((@size*@count) <= @wrapper) // 3*340 <= 830 is false

生成的 CSS(带有工作解决方案,大包装器)

.test_col_fixed {
    width: 340px;
    margin-right: 90px;
}
Run Code Online (Sandbox Code Playgroud)

Sma*_*tti 2

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;
    }
}
Run Code Online (Sandbox Code Playgroud)