美文网首页
Stylus预处理器简介(十三)@IMPORT 和 @REQUI

Stylus预处理器简介(十三)@IMPORT 和 @REQUI

作者: 曲昶光 | 来源:发表于2021-07-28 10:06 被阅读0次

@IMPORT 和 @REQUIRE

Stylus支持@import CSS字面值, 也支持其他Stylus样式的动态导入。

字面CSS(Literal CSS)

任何.css扩展的文件名将作为字面量。例如:

@import "reset.css"

渲染CSS 字面值@import如下所示:

 @import "reset.css"

Stylus式导入(Stylus Import)

免责声明:在所有与Stylus表一起使用的地方,都可以使用@require
当使用@import没有.css扩展名,则会被认为是Stylus片段(如:@import "mixins/border-radius")。

@import 工作原理为:遍历目录队列,并检查任意目录中是否有该文件(类似node的require.paths)。该队列默认为单一路径,从filename选项的dirname衍生而来。 因此,如果你的文件名是/tmp/testing/stylus/main.styl,导入将显现为/tmp/testing/stylus/。

@import还支持索引样式。这意味着当你@import blueprint时,它将解析任意一个蓝图。/ index.styl styl或蓝图。这对于那些想要公开所有特性,同时仍然允许导入特性子集的库来说非常有用。

例如,一个常见的lib结构可能是:

./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);
    });

Require

除了@import, Stylus还有@require。它几乎以相同的方式工作,除了只导入一次给定的文件

Block-level import

Stylus支持块级导入。这意味着您不仅可以在根级别使用@import,还可以嵌套在其他选择器或at-rules中。
如果你有一个酒吧。样式与以下代码:

.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;
  }
}

File globbing

Stylus支持通配符。使用它,你可以导入许多文件使用文件蒙版:

@import 'product/*'

这将以这样的结构从产品目录中导入所有的' stylus '表:

./product
  |-- body.styl
  |-- foot.styl
  |-- head.styl

注意,这也适用于@require,所以如果你也有。/product/index。样式与此内容:

@require 'head'
@require 'body'
@require 'foot'

然后@require 'product/*'将只包含每个单独的表单一次。

解析导入中的相对url

默认情况下,Stylus不会解析导入的. style文件中的url,所以如果你碰巧有一个' foo.styl'与@import "bar/bar。样式,它将有url("baz.png"),它将是url("baz.png")在结果的CSS。

但是你可以通过使用——resolve-url(或-r) CLI选项来改变这种行为,在你的CSS中获取url("bar/baz.png")。

JavaScript Import 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')

相关文章

网友评论

      本文标题:Stylus预处理器简介(十三)@IMPORT 和 @REQUI

      本文链接:https://www.haomeiwen.com/subject/ilzlmltx.html