Skip to content
On this page

url()

内联Data URI图像

Stylus捆绑了一个可选函数,名叫url(),其替换了字面上的url()调用(且使用base64 Data URIs有条件地内联它们)。

示例

通过require('stylus').url该函数本身是可用的,其接受一个options对象,当看到url()时候,返回Stylus内部调用的函数。

.define(name, callback)方法指定了一个可被调用的JavaScript函数。在这种情况下,因为我们图片在./css/images中,我们可以忽视paths选项(默认情况下,会查找相关要呈现的图像文件)。如果愿意,该行为时可以改变的:

stylus(str)
  .set('filename', __dirname + '/css/test.styl')
  .define('url', stylus.url())
  .render(function(err, css){
    // render it
  });
stylus(str)
  .set('filename', __dirname + '/css/test.styl')
  .define('url', stylus.url())
  .render(function(err, css){
    // render it
  });

例如,想象图片在./public/images, 我们想要使用url(images/tobi.png), 我们可以传递paths公共目录。这样,它就成为了向上查找进程的一部分。

同样,如果我们想替换为url(tobi.png), 我们可以传递paths: [__dirname + '/public/images'].

stylus(str)
  .set('filename', __dirname + '/css/test.styl')
  .define('url', stylus.url({ paths: [__dirname + '/public'] }))
  .render(function(err, css){
    // render it
  });
stylus(str)
  .set('filename', __dirname + '/css/test.styl')
  .define('url', stylus.url({ paths: [__dirname + '/public'] }))
  .render(function(err, css){
    // render it
  });

utf8 encoding for SVGs

Since base64 encoding an image actually increases the original size, you have the option to use utf8 encoding when inlining SVGs.

There is a bif for this: embedurl:

.embed-with-utf8 {
  background-image: embedurl("circle.svg", "utf8");
}
.embed-with-utf8 {
  background-image: embedurl("circle.svg", "utf8");
}

Would result in utf-encoded inline SVG instead of base64 one.

If you'd like to use the JS define so you could use the paths alongside the utf encoding, you'll need to define it using another name, not url(). This is Due to how url() function is parsed in Stylus: it is impossible now to pass the extra param to it, so you couldn't just call url with the second param to set the encoding. But if you'd define the url with another name:

stylus(str)
  .set('filename', __dirname + '/css/test.styl')
  .define('inline-url', stylus.url({ paths: [__dirname + '/public'] }))
  .render(function(err, css){
    // render it
  });
stylus(str)
  .set('filename', __dirname + '/css/test.styl')
  .define('inline-url', stylus.url({ paths: [__dirname + '/public'] }))
  .render(function(err, css){
    // render it
  });

You could then use inline-url bif just like you can use embedurl, but with an added paths functionality:

.embed-with-utf8-at-path {
  background-image: inline-url("tobi.svg", "utf8");
}
.embed-with-utf8-at-path {
  background-image: inline-url("tobi.svg", "utf8");
}

选项(Options)

  • limit 大小默认限制30Kb(30000), 使用 false 关闭限制
  • paths 图像解析路径