L3F.WIN

Github及Hexo的使用

0%

学习stylus【11】@IMPORT 和 @REQUIRE

@IMPORT 和 @REQUIRE

Stylus 支持CSS的关键字@import,以及动态导入其他Stylus表。

关键字CSS

任何.css扩展的文件名将作为关键字的值。例如:

1
2
3
@import "reset.css"
=>
@import "reset.css"

导入Stylus

免责声明:在@import所有的地方都使用stylus,也可以使用@require
当使用不带.css扩展名的@import时,它被假定使用stylus(例如@import”mixins/border-radius”)。
@import可以通过遍历目录来工作,并检查这个文件是否存在于其中任何一个目录中(类似于node的require.paths)。 此数组默认为单个路径,该路径是从文件名选项的dirname派生的。 因此,如果您的文件名是/tmp/testing/stylus/main.styl,那么导入将会在/tmp/testing/stylus/中查找。
@import也支持索引样式。 这意味着当你@import blueprint,它将解析成blueprint.styl或blueprint/index.styl。 这对于想要公开其所有功能的库非常有用,同时仍允许导入功能子集。
例如,一个常见的库结构:

1
2
3
4
5
./tablet
|-- index.styl
|-- vendor.styl
|-- buttons.styl
|-- images.styl

在下面的例子中,我们设置了路径选项来为Stylus提供额外的路径。 在./test.styl中,我们可以使用@import”mixins/border-radius”或@import”border-radius”(因为./mixins暴露给Stylus)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 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);
});

Require

@import之后,Stylus也推出了@require。 它几乎以相同的方式工作,除了只导入任何给定文件一次。

块级导入(Block-level import)

Stylus支持块级导入。 这意味着你不仅可以在根级别使用@import,而且可以嵌套在其他选择器或规则中。
代码bar.styl:

1
2
.bar
width: 10px;

然后你可以像这样在foo.styl里面导入它:

1
2
3
4
5
.foo
@import 'bar.styl'

@media screen and (min-width: 640px)
@import 'bar.styl'

你会得到这个编译好的CSS结果:

1
2
3
4
5
6
7
8
.foo .bar {
width: 10px;
}
@media screen and (min-width: 640px) {
.bar {
width: 10px;
}
}

文件通配符(File globbing)

Stylus支持通配符。 有了它,你可以使用文件掩码导入许多文件:

1
@import 'product/*'

这将从这个结构的目录中导入所有的Stylus表:

1
2
3
4
./product
|-- body.styl
|-- foot.styl
|-- head.styl

通配符也适用于@require 所以如果你有一个./product/index.styl这个内容:

1
2
3
@require 'head'
@require 'body'
@require 'foot'

那么@require’product/*’将只包含一次单个表。

解析导入中的相关URL

默认情况下,Stylus不能解析导入的.styl文件中的url,所以如果你碰巧有一个带有@import“bar/bar.styl”的foo.styl,它含有url(“baz.png”),它在得到的CSS中也会是url(“baz.png”)。
但是你可以通过使用–resolve-url(或者只是-r)CLI选项在你的结果CSS中获取url(“bar/baz.png”)来改变这种行为。

JavaScript导入API

当使用.import(path)方法,这些导入是被推迟的,直到赋值。

1
2
3
4
5
6
7
8
9
10
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);
});

下面的代码

1
2
3
@import 'mixins/vendor'
=>
.import('mixins/vendor')