sjs 代码可以编写在 xhsml 文件中的 sjs 标签内,或以 .sjs 为后缀名的文件内。
每一个 .sjs 文件是一个单独的模块。
每个模块都有自己独立的作用域。即在一个模块里面定义的变量与函数,默认为私有的,对其他模块不可见。
一个模块要想对外暴露其内部的私有变量与函数,只能通过 module.exports 实现。
在小红书开发者工具里面,右键可以直接创建 .sjs 文件,在其中直接编写 sjs 脚本。
示例代码:
// /pages/comm.sjs var foo = "'hello world' from comm.sjs"; var bar = function(d) { return d; } module.exports = { foo: foo, bar: bar };
上述例子在 /pages/comm.sjs 的文件里面编写了 sjs 代码。该 .sjs 文件可以被其他的 .sjs 文件 或 .xhsml 中的 sjs 标签引用。
每个 sjs 模块均有一个内置的 module 对象。
exports: 通过该属性,可以对外共享本模块的私有变量与函数。 示例代码:
// /pages/tools.sjs var foo = "'hello world' from tools.sjs"; var bar = function (d) { return d; } module.exports = { foo: foo, bar: bar, }; module.exports.msg = "some msg";
<!-- page/index/index.xhsml --> <sjs src="./../tools.sjs" module="tools" /> <view> {{tools.msg}} </view> <view> {{tools.bar(tools.foo)}} </view>
页面输出:
some msg 'hello world' from tools.sjs
在 .sjs 模块中引用其他 sjs 文件模块,可以使用 require 函数。
示例代码:
// /pages/tools.sjs var foo = "'hello world' from tools.sjs"; var bar = function (d) { return d; } module.exports = { foo: foo, bar: bar, }; module.exports.msg = "some msg"; // /pages/logic.sjs var tools = require("./tools.sjs"); console.log(tools.foo); console.log(tools.bar("logic.sjs")); console.log(tools.msg);
<!-- /page/index/index.xhsml --> <sjs src="./../logic.sjs" module="logic" />
控制台输出:
'hello world' from tools.sjs logic.sjs some msg
属性名 | 类型 | 说明 |
---|---|---|
module | string | module 属性值的命名必须符合下面两个规则:首字符必须是:字母(a-zA-Z),下划线 _ 剩余字符可以是:字母(a-zA-Z),下划线 _, 数字(0-9) |
在单个 xhsml 文件内,建议其值唯一。有重复模块名则按照先后顺序覆盖(后者覆盖前者)。 | ||
src | string | 引用 .sjs 文件的相对路径,不支持表达式 |
sjs 模块只能在定义模块的 xhsml 文件中被访问到。使用 include 或 import 时,sjs 模块不会被引入到对应的 xhsml 文件中。 template 标签中,只能使用定义该 template 的 xhsml 文件中定义的 sjs 模块。