JavaScript API
约 1416 字大约 5 分钟
2025-04-22
只需通过 require
引入模块,然后调用 render()
方法并传入 Stylus 代码字符串和(可选的)options
配置对象。
使用 Stylus 的框架应该传递 filename
选项以提供更好的错误报告。
var stylus = require("stylus");
stylus.render(str, { filename: "nesting.css" }, function (err, css) {
if (err) throw err;
console.log(css);
});
我们也可以采用更渐进式的方式实现同样的功能:
var stylus = require("stylus");
stylus(str)
.set("filename", "nesting.css")
.render(function (err, css) {
// logic
});
一、.set()
应用设置
.set()
是 Stylus JavaScript API 中的一个方法,用于在编译 Stylus 代码时设置全局变量或选项。
设置编译选项
stylus(str) .set("compress", true) // 压缩输出 .set("linenos", true) // 显示行号 .set("firebug", true); // 添加Firebug路径注释
定义全局变量
stylus(str) .set("primary-color", "#3498db") .set("font-stack", "Helvetica, Arial, sans-serif");
设置路径信息
stylus(str) .set("filename", "styles.styl") // 影响相对路径解析 .set("paths", ["/public/css", "/assets"]); // 设置查找路径
二、.include()
.include()
是 .set('paths',...)
的一种渐进式替代方案。当需要引入暴露路径的外部 Stylus 库时,这种方法特别理想。
stylus(str)
.include(require('nib').path)
.include(process.env.HOME + '/mixins')
.include(__dirname + '/styles') // 添加查找路径
.include('node_modules') // 可以添加多个路径
.render(...)
三、.import()
导入文件
.import()
是 Stylus JavaScript API 中的一个方法,用于在编译前强制导入指定的 Stylus 文件,类似于在 Stylus 代码中使用 @import 指令,但通过 JavaScript 控制导入时机和顺序。
var stylus = require("../"),
const fs = require('fs');
const path = require('path');
const stylus = require('stylus');
const css = fs.readFileSync('main.styl', 'utf8');
stylus(css)
.set('filename', 'main.styl')
.include(path.join(__dirname, 'styles'))
.import('variables.styl') // 从 include 路径查找
.import('mixins/utilities.styl')
.render(function(err, css) {
if (err) throw err;
fs.writeFileSync('main.css', css);
});
四、.define()
定义变量
.define()
是 Stylus JavaScript API 中的一个方法,用于在编译 Stylus 代码时定义全局变量。
1、基础语法
.define(name, node)
name
(String): 在 Stylus 中定义的变量名。node
(Node|Function|Value): 可以是:- Stylus 的 AST 节点对象
- JavaScript 函数
- 原始值(会自动转换为节点)
Stylus 会自动将 JavaScript 值转换为对应的 Stylus 类型(在可能的情况下)。以下是几个示例:
stylus(str)
.define("string", "some string")
.define("number", 15.5)
.define("some-bool", true)
.define("list", [1, 2, 3])
.define("list", [1, 2, [3, 4, [5, 6]]])
.define("list", { foo: "bar", bar: "baz" })
.define("families", ["Helvetica Neue", "Helvetica", "sans-serif"]);
同样的规则也适用于 JavaScript 的函数:
stylus(str).define("get-list", function () {
return ["foo", "bar", "baz"];
});
.define(name, fn)
方法允许你将 JavaScript 定义的函数提供给 Stylus。你可以把这些函数看作是 JavaScript 与 Stylus 之间的桥梁。当遇到 Stylus 本身无法实现的功能时,就可以通过 JavaScript 来定义它!
在这个例子中,我们定义了四个函数:add()
、sub()
、image-width()
和 image-height()
。这些函数必须返回一个 Node
节点对象,相关的构造函数和其他节点类型都可以通过 stylus.nodes
获取。
var stylus = require("../");
var nodes = stylus.nodes;
var utils = stylus.utils;
var fs = require("fs");
function add(a, b) {
return a.operate("+", b);
}
function sub(a, b) {
return a.operate("-", b);
}
function imageDimensions(img) {
// assert that the node (img) is a String node, passing
// the param name for error reporting
utils.assertType(img, "string", "img");
var path = img.val;
// Grab bytes necessary to retrieve dimensions.
// if this was real you would do this per format,
// instead of reading the entire image :)
var data = fs.readFileSync(__dirname + "/" + path);
// GIF
// of course you would support.. more :)
if ("GIF" == data.slice(0, 3).toString()) {
var w = data.slice(6, 8),
h = data.slice(8, 10);
w = (w[1] << 8) | w[0];
h = (h[1] << 8) | h[0];
}
return [w, h];
}
function imageWidth(img) {
return new nodes.Unit(imageDimensions(img)[0]);
}
function imageHeight(img) {
return new nodes.Unit(imageDimensions(img)[1]);
}
stylus(str)
.set("filename", "js-functions.styl")
.define("add", add)
.define("sub", sub)
.define("image-width", imageWidth)
.define("image-height", imageHeight)
.render(function (err, css) {
if (err) throw err;
console.log(css);
});
如需进一步参考(在文档完善前),请查看以下文件:
lib/nodes/*
lib/utils.js
五、.use()
插件
.use()
是 Stylus JavaScript API 中用于扩展编译器功能的核心方法,允许你为 Stylus 添加自定义插件或功能扩展。以下是该方法的全面解析:
1、基础语法
stylus(cssString)
.use(plugin) // 添加插件
.use(pluginWithOptions, options) // 添加插件并传入配置
.render(callback);
plugin
: Function 必须包含.attach()
方法的插件函数options
: Object (可选) 传递给插件的配置对象
var mylib = function(style){
style.define('add', add);
style.define('sub', sub);
};
stylus(str)
.use(mylib)
.render(...)
当调用带有选项的render()
方法时,可以通过use
选项传入一个函数或函数数组,这些函数将会在渲染器中被调用。
stylus.render(str, { use: mylib }, function (err, css) {
if (err) throw err;
console.log(css);
});
六、.deps()
获取文件依赖
.deps()
是 Stylus JavaScript API 中用于获取文件依赖关系的方法,它可以帮助你分析 Stylus 文件的依赖图谱。
1、基本用法
const stylus = require("stylus");
const fs = require("fs");
const css = fs.readFileSync("main.styl", "utf8");
stylus(css)
.set("filename", "main.styl")
.deps(function (err, deps) {
if (err) throw err;
console.log(deps); // 输出依赖文件数组
});
2、返回值
.deps()
回调函数返回的 deps
参数是一个数组,包含以下信息:
[
{
path: '/absolute/path/to/main.styl', // 文件绝对路径
mtime: Date // 文件修改时间
},
{
path: '/absolute/path/to/_variables.styl',
mtime: Date
}
// 更多依赖文件...
]
七、.resolver()
解析器
resolver()
是 Stylus 中用于自定义模块解析逻辑的 API,它允许你控制 Stylus 如何查找和解析 @import
引入的文件。
const stylus = require("stylus");
const myResolver = stylus.resolver({ options });
stylus(css).use(myResolver).render(callback);
选项 | 类型 | 默认值 | 说明 |
---|---|---|---|
paths | Array | [] | 自定义查找路径 |
extensions | Array | ['.styl', '.css'] | 支持的文件扩展名 |
prefix | String | '_' | 前缀匹配规则 |
nocheck | Boolean | false | 是否跳过文件存在性检查 |
如果不自定义解析器,Stylus 使用以下规则:
- 检查路径是否以
.styl
或.css
结尾 - 尝试添加扩展名(
.styl
、.css
) - 尝试添加
_
前缀(如_colors.styl
) - 按
paths
顺序查找
更新日志
e7112
-1于