sjs(safe/subset javascript)是小程序定义的一套脚本语言,由它导出的变量/函数可以 。
语言概述
语法定义
sjs 是 javascript 语言的子集,并不等同于 javascript。具体可参考:
模块管理
- sjs 文件的扩展名必须为
.sjs
,每个 .sjs 文件为一个模块,使用 export 导出变量和函数,使用 import 引入依赖的其他 sjs 模块(请勿省略文件扩展名)。
- sjs 也可引用 npm 包,但只能引用其中的 .sjs 文件。
运行环境
- sjs 运行在小程序渲染层,与小程序的 javascript 运行环境(逻辑层)隔离,因而不能调用 js 文件中定义的函数,也不能调用小程序提供的 api。
- sjs 中定义的函数可用于响应基础组件的事件以避免逻辑层和渲染层的频繁通信,但有一定的限制,详见 sjs 响应事件。
使用示例
num.tofixed(2);\nconst five = 5;\nexport default {\n message,\n format,\n five\n};"}" id="ce943a71">
// pages/index/foo.sjs const message = 'hello sjs'; const format = num => num.tofixed(2); const five = 5; export default { message, format, five };
// pages/index/bar.sjs import { five } from './foo.sjs'; export const x = 3; export const y = 4 five;
// pages/index/index.js page({ data: { message: 'hello javascript', value: 3.14159, }, });
\n\n\njs message: {{message}} \nsjs message: {{m.message}} \nformatted value: {{m.format(value)}} \n\nx: {{x}} \nz: {{z}} "}" id="6c14a0b0">
<import-sjs from="./foo.sjs" name="m" /> <import-sjs from="./bar.sjs" name="{x, y: z}" /> <view>js message: {{message}}view> <view>sjs message: {{m.message}}view> <view>formatted value: {{m.format(value)}}view> <view>x: {{x}}view> <view>z: {{z}}view>
页面渲染结果:
js message: hello javascript sjs message: hello sjs formatted value: 3.14 x: 3 z: 9