css - 更少的导入 - 引用与一次

标签 css import less

情况

我正在为一个由开发团队(而不是一个开发人员)构建的新网站设置一些框架。我当前的 CSS 设置使用以下 LESS 文件:

  • grid.less
  • mixins.less
  • style.less
  • template-home.less
  • template-destination.less
  • 其他特定于模板的文件

文件 style.less 导入所有内容:

@import "grid.less";
@import "mixins.less";
@import "template-home.less";
@import "template-destination.less";

解决方法

在我看来,这是一种相当明显且常见的方法 - 然而,如果我想在其中一个 template-* 文件中使用定义的 mixin,LESS 无法编译该文件,因为 NameError: .exampleMixin 未定义

通读文档,我似乎有两个选择,这两个选择都涉及将我的 mixins.less 导入到可能使用它的 each 模板文件中。我可以添加:

// either reference the file
@import (reference) "mixins.less";
// or use once
@import (once) "mixins.less";

问题

我了解它们各自的作用,但它们各自的优缺点是什么?为什么我不能将混入导入全局 style.less 并在每个其他包含的文件中使用它们?

最佳答案

Why I can't just import the mixins to the global style.less and use them in each of the other included files?

此方法应该可以正常工作,不会出现任何编译错误。只有当你试图在没有 mixins.less 的情况下编译 template-*.less 时,它才会大惊小怪。你得到一个错误检查 mixins.less 的位置是否正确。

一次并引用

I understand what each of these is doing, but what are the pros & cons of each?

一次

一次的原则是只导入一个文件一次。例如,您可能在 template-*.less 文件和 styles.less 中都导入了 mixins.less。这将防止文件被多次导入,从而导致样式表中出现重复的 css 样式。

值得注意的是,once 实际上是import 的默认行为,因此不需要指定。

引用

引用非常巧妙。如果你导入引用,编译时它只会输出导入文件中已经在父 less 文件中使用过的样式。通常这将用于混合类和扩展类。

示例

//Mixins.less
.m-bacon {
   color: red;
}

.m-smokey {
   color: pink;
}

// Styles.less
@import (reference) mixins.less;

.pork {
    .m-bacon;
}

如果 styles.less 被编译,它只会包含 pork 类。

//Output
.pork {
    color: red;
}

总结

总而言之,once 防止多次生成相同的样式。这也是 @import 的默认行为。 reference 防止在编译时生成未引用的混合类和扩展类。

关于css - 更少的导入 - 引用与一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24035513/

相关文章:

javascript - 折叠 div 时 float 背景

python - Python 中的 imp.load_source()

html - Bootstrap 3 with Less - 我如何设法使容器水平和垂直居中

html - 使用 flex 截断文本溢出

JavaScript 游戏 - 无法通过 0.5 像素偏移和错误边界渲染进入中心圆圈

html - 图层不会拉伸(stretch)到包含图像的高度

python : how to import module in other module

css - 使用 less 变量输出字体属性时出现问题

css - 如何使 Zurb 电子邮件*无*响应

python - Flask_mysql 给出错误 "ExtDeprecationWarning: Detected extension named flaskext.mysql please rename it to flask_mysql."