外部文件函数 待完善
约 435 字大约 1 分钟
2025-04-20
一、json()
导入 json
使用 json()
函数可以导入外部 JSON 文件中的变量和对象。嵌套对象可以使用破折号(-
)连接。 可选参数:
hash
:将 JSON 对象转换为哈希对象。leave-strings
:保留字符串值。optional
:如果 JSON 文件不存在,则返回null
,防止编译报错。
例如,以下示例 media-queries.json
文件:
{
"small": "screen and (max-width:400px)",
"tablet": {
"landscape": "screen and (min-width:600px) and (orientation:landscape)",
"portrait": "screen and (min-width:600px) and (orientation:portrait)"
}
}
可以通过以下方式使用:
json('media-queries.json')
@media small
// => @media screen and (max-width:400px)
@media tablet-landscape
// => @media screen and (min-width:600px) and (orientation:landscape)
参数使用介绍:
{
"icon": "icon.png"
}
如下使用:
vars = json('vars.json', { hash: true })
body
width: vars.width
vars = json('vars.json', { hash: true, leave-strings: true })
typeof(vars.icon) // => 'string'
// don't throw an error if the JSON file doesn't exist
optional = json('optional.json', { hash: true, optional: true })
typeof(optional) // => 'null'
二、use()
导入 js 插件
在 Stylus 中,.use()
方法是用于 加载插件 或 扩展 Stylus 功能 的核心 API。它允许你在编译过程中注入自定义逻辑,例如添加新函数、修改解析规则或集成第三方工具。
use("plugins/add.js")
width add(10, 100)
// => width: 110
本例中的 add.js
插件如下所示:
var plugin = function(){
return function(style){
style.define('add', function(a, b) {
return a.operate('+', b);
});
};
};
module.exports = plugin;
如果你想返回任何 Stylus 对象,例如 RGBA
、Ident
或 Unit
,你可以使用提供的 Stylus 节点,如下所示:
var plugin = function(){
return function(style){
var nodes = this.nodes;
style.define('something', function() {
return new nodes.Ident('foobar');
});
};
};
module.exports = plugin;
你可以使用哈希对象将任何选项作为可选的第二个参数传递:(暂时没有查到相关的文档和例子)
use("plugins/add.js", { foo: bar })
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于