SJS introduction

更新时间:
复制 MD 格式

Safe/Subset JavaScript (SJS) is a custom scripting language for miniapps that lets you build page structures in AXML.

SJS is a subset of JavaScript, but it is a separate language with a different syntax. Do not treat SJS as JavaScript.

Usage

Define SJS in an .sjs file:

// pages/index/index.sjs
const message = 'hello alipay';
const getMsg = x => x;
export default {
  message,
  getMsg,
};
// pages/index/index.js
Page({
  data: {
    msg: 'hello taobao',
  },
});
<!-- pages/index/index.axml -->
<import-sjs name="m1" from="./index.sjs"/>
<view>{{m1.message}}</view>
<view>{{m1.getMsg(msg)}}</view>

Page output:

hello alipay
hello taobao
Note

  • SJS can only be defined in .sjs files, which are then imported into AXML using the <import-sjs> tag.

  • SJS can call functions defined in other .sjs files.

  • SJS is a subset of JavaScript. Do not treat it as JavaScript.

  • The SJS runtime environment is isolated from other JavaScript code. SJS cannot call functions defined in other JavaScript files or call the APIs provided by the miniapp.

  • SJS functions cannot be used as component event callbacks.

  • SJS does not depend on the base library version and can run in all miniapp versions.

The import-sjs tag

Property

Type

Required

Description

name

String

Yes

The module name for the current <import-sjs> tag.

from

String

Yes

The relative path of the .sjs file to import.

Note

  • The name property specifies the module name for the current <import-sjs> tag. Each name must be unique within an AXML file. If duplicate module names exist, the latter import overwrites the former. Module names in different AXML files do not conflict with each other.

  • The name property can be a string for the default module export, or use the {x} syntax for named exports.

Sample code:

// pages/index/index.js
Page({
  data: {
    msg: 'hello alipay',
  },
});
// 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>
<!-- You can also use a self-closing tag
<import-sjs from="./index.sjs" name="test" />
-->

<!-- Call the bar function from the test module with test.foo as the parameter -->
<view> {{test.bar(test.foo)}} </view>
<!-- Call the bar function from the test module with msg from page/index/index.js as the parameter -->
<view> {{test.bar(msg)}} </view>

<!-- Named export is supported -->
<import-sjs from="./namedExport.sjs" name="{x, y: z}" />
<view>{{x}}</view>
<view>{{z}}</view>

Page output:

foo
hello alipay
3
4
Note

  • You must use the .sjs file extension for imports.

  • An .sjs module that is defined but never imported is not parsed or run.