【问题标题】:How to avoid Duplication of CSS Classes while compile LESS to CSS如何在将 LESS 编译为 CSS 时避免 CSS 类的重复
【发布时间】:2025-12-14 16:35:01
【问题描述】:

我在开发 css 时使用较少的文件,但是当我编译为 css base.less 时,可以多次编译,例如:

style.less
   @import 'base.less'
   @import 'variable.less'
   @import '../../dashboard/my-dashboard.less'

my-dashboard.less
   @import 'base.less'
   .my-dashboard-css{
     all css goes here
}

在将 style.less 编译为 style.css 时,想从“my-dashboard.less”中跳过 base.less,但我想导入 base.less 以供开发人员参考。请建议我如何避免我。 Ihv 也尝试过 @import(once) 但它不起作用。

【问题讨论】:

  • 不能全局导入吗?
  • 不,我想保留组件驱动的文件夹系统。我的仪表板是我的组件。想要将我所有的仪表板资源保存在一个文件夹中,将常用变量和基础文件保存在另一个文件夹中。

标签: html css gruntjs less


【解决方案1】:

您只能使用关键字 reference: @import (reference) "foo.less"; 导入引用。

http://lesscss.org/features/#import-options

【讨论】:

    【解决方案2】:

    我同意@3rdthemagical 的回答。因此,对于您的答案,请按照链接作为您的指南。

    这可能是你最后的输出。

    style.less
       @import (reference) 'base.less'
       @import (reference) 'variable.less'
       @import (less) '../../dashboard/my-dashboard.less'
    
    my-dashboard.less
       @import (reference) 'base.less'
       .my-dashboard-css{
         all css goes here
    }
    

    这是我实际的 LESS CSS

    // CodeKit Framework Libraries [Bootstrap]
    @import (reference) "utilities";
    @import (reference) "variables";
    @import (reference) "mixins";
    
    // Internal Libraries
    @import (less) "_fonts";
    @import (less) "_mixins";
    @import (less) "components/default";
    @import (less) "components/menu";
    @import (less) "components/header";
    @import (less) "components/footer";
    
    @import (less) "components/core";
    

    注意:reference 下的所有内容都是我的变量和 mixins。如果您将导入声明为less,它将读取文件并将其导入为较少的内容。

    【讨论】:

    • 感谢您的解决方案。我的问题通过使用最新的 Grunt 软件包版本得到解决,我正在使用 1.4.0 。它将自动从 Output.CSS 中删除重复导入的 Less 文件。
    最近更新 更多