4

问题

有没有办法(以编程方式)在 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);
}

生成的 CSS(小包装器)

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

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

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

1 回答 1

1

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;
    }
}
于 2015-06-16T10:55:59.890 回答