SJS Introduction
SJS (safe/subset javascript) is a set of custom scripting language of Mini Program and used to build page structure in AXML.
The SJS is a subset of JavaScript language, which is a different language from JavaScript, has syntax different from JavaScript.
Usage
Define SJS in .sjs
file:
// pages/index/index.sjs
const message = 'hello world';
const getMsg = x => x;
export default {
message,
getMsg,
};
// pages/index/index.js
Page({
data: {
msg: 'hello Mini Program',
},
});
<!-- pages/index/index.axml -->
<import-sjs name="m1" from="./index.sjs"/>
<view>{{m1.message}}</view>
<view>{{m1.getMsg(msg)}}</view>
Page output:
hello world
hello Mini Program
Note:
- The sjs only support import and export to manage dependency.
- The sjs can be defined in the
.sjs
file only. It is then introduced through the<import-sjs>
tag in axml.
- The sjs can call functions defined in other sjs files.
- The sjs is a subset of JavaScript language and cannot be regarded as the same as JavaScript.
- The running environment of sjs is isolated from the other JavaScript codes. In sjs, it is impossible to call functions defined in other JavaScript files or APIs provided by Mini Program.
- The sjs function cannot be called back as component event.
- The sjs is independent of the base library version and can run in all versions of Mini Program.
import-sjs Tag
Property | Type | Required | Description |
name | String | Yes | Module name of the current <import-sjs> tag. |
from | String | Yes | Relative path of the reference .sjs file. |
Note:
The name attribute is the module name of the current <import-sjs>
tag. In a single AXML file, unique name value is recommended. If there are repeated module names, the latter overrides the former. The <import-sjs>
module names in different AXML files do not override each other.
The name attribute can be a string to indicate the default module name or {x}
to indicate the export of named module.
Sample codes:
// pages/index/index.js
Page({
data: {
msg: 'hello world',
},
});
// pages/index/index.sjs
function bar(prefix) {
return prefix;
}
export default {
foo: 'foo',
bar: bar,
};
// pages/index/namedExport.sjs
export const x = 3;
export const y = 4;
<!-- pages/index/index.axml -->
<import-sjs from="./index.sjs" name="test"></import-sjs>
<!-- Possible to code as a single tag closure -->
<import-sjs from="./index.sjs" name="test" />
<!-- Call the bar function in the test module, with parameter as foo in the test module -->
<view> {{test.bar(test.foo)}} </view>
<!-- Call the bar function in the test module, with parameter as msg in page.js -->
<view> {{test.bar(msg)}} </view>
<!-- Support named export (named export) -->
<import-sjs from="./namedExport.sjs" name="{x, y: z}" />
<view>{{x}}</view>
<view>{{z}}</view>
Page output:
foo
hello world
3
4
Note:
- In reference, be sure to use the “.sjs” file suffix.
- If a .sjs module was defined but has never been referred, the module is not parsed or run.