@import 和 @require
Stylus 支持 CSS 的字面量 @import,以及其他 Stylus 样式表的动态导入或要求。
字面量 CSS
任何带有 .css 扩展名的文件名都将成为字面量。例如:
@import "reset.css"
渲染下面的字面量 CSS @import:
@import "reset.css"
Stylus 导入
免责声明:在所有使用 Stylus 样式表的地方,都可以使用 @require
当使用没有 .css 扩展名的 @import 时,它被认为是一个 Stylus 样式表(例如,@import "mixins/border-radius")。
@import 通过迭代目录数组,并检查该文件是否存在于其中任何一个目录中(类似于 node 的 require.paths)来工作。该数组默认为单个路径,该路径源自 filename 选项的 dirname。因此,如果您的文件名是 /tmp/testing/stylus/main.styl,则导入将在 /tmp/testing/stylus/ 中查找。
@import 还支持索引样式。这意味着当您 @import blueprint 时,它将解析 要么 blueprint.styl 要么 blueprint/index.styl。这对于希望公开其所有功能,同时仍允许导入功能子集的库非常有用。
例如,常见的库结构可能是:
./tablet
|-- index.styl
|-- vendor.styl
|-- buttons.styl
|-- images.styl
在下面的示例中,我们设置了 paths 选项以提供额外的 Stylus 路径。然后,在 ./test.styl 中,我们可以 @import "mixins/border-radius" 或 @import "border-radius"(因为 ./mixins 对 Stylus 可见)。
/**
* Module dependencies.
*/
var stylus = require("../"),
str = require("fs").readFileSync(__dirname + "/test.styl", "utf8");
var paths = [__dirname, __dirname + "/mixins"];
stylus(str)
.set("filename", __dirname + "/test.styl")
.set("paths", paths)
.render(function (err, css) {
if (err) throw err;
console.log(css);
});
要求
除了 @import,Stylus 还有 @require。它的工作方式几乎相同,唯一的区别是只导入任何给定文件一次。
块级导入
Stylus 支持块级导入。这意味着您不仅可以在根级别使用 @import,还可以在其他选择器或 at-rules 中嵌套使用。
如果您有一个带有以下代码的 bar.styl:
.bar
width: 10px;
那么您可以在 foo.styl 中像这样导入它:
.foo
@import 'bar.styl'
@media screen and (min-width: 640px)
@import 'bar.styl'
编译后的 CSS 如下:
.foo .bar {
width: 10px;
}
@media screen and (min-width: 640px) {
.bar {
width: 10px;
}
}
文件匹配
Stylus 支持 globbing。你可以使用文件掩码导入多个文件:
@import 'product/*'
这将导入 product 目录中的所有 stylus 文件,目录结构如下:
./product
|-- body.styl
|-- foot.styl
|-- head.styl
请注意,这也适用于 @require,因此如果你还有一个 ./product/index.styl 文件,其内容如下:
@require 'head'
@require 'body'
@require 'foot'
那么 @require 'product/*' 将只包含每个单独的样式表一次。
解析导入中的相对 URL
默认情况下,Stylus 不会解析导入的 .styl 文件中的 URL,因此如果你有一个 foo.styl 文件,其中包含 @import "bar/bar.styl",而 bar/bar.styl 中包含 url("baz.png"),则在生成的 CSS 中也会是 url("baz.png")。
但是,你可以使用 --resolve-url(或 -r)CLI 选项来更改此行为,以在生成的 CSS 中获得 url("bar/baz.png")。
JavaScript 导入 API
使用 .import(path) 方法时,这些导入会被推迟到评估时:
var stylus = require("../"),
str = require("fs").readFileSync(__dirname + "/test.styl", "utf8");
stylus(str)
.set("filename", __dirname + "/test.styl")
.import("mixins/vendor")
.render(function (err, css) {
if (err) throw err;
console.log(css);
});
以下语句...
@import 'mixins/vendor'
...等同于...
.import('mixins/vendor')