模块与 require
page.js、自定义组件 JS、任务脚本都可以 require 公共文件,规则相同。界面侧还有一份最短示例:require。
引擎是 Rhino 1.8:用 module.exports 导出,不要写 import / export。
路径
| 写法 | 基准 | 说明 |
|---|---|---|
./、../(推荐) | 当前 JS 所在目录 | 同目录、上级、公共模块都优先这样写 |
不以 ./、../ 开头 | 项目根目录 | 相对项目根的绝对路径 |
your-project/
deekeScript.json
common/
hello.js
pages/home/
page.js
tasks/
follow.js| 当前文件 | 推荐 |
|---|---|
tasks/follow.js → common/hello.js | require('../common/hello.js') |
pages/home/page.js → common/hello.js | require('../../common/hello.js') |
pages/home/page.js → 同目录 helper | require('./helper.js') |
tasks/a.js → tasks/b.js | require('./b.js') |
与 Engines.executeScript 的区别
| API | 路径基准 | 示例 |
|---|---|---|
require | 优先相对当前文件 | require('../common/x.js') |
Engines.executeScript | 相对项目根 | Engines.executeScript('tasks/x.js') |
导出
javascript
// common/hello.js
module.exports = {
text: '你好',
greet: function (name) {
return '你好,' + name;
}
};在页面里用
javascript
// pages/home/page.js
let hello = require('../../common/hello.js');
Page({
data: {
hint: hello.text
}
});在任务脚本里用
javascript
// tasks/follow.js
let hello = require('../common/hello.js');
System.toast(hello.text);注意
- 必须带
.js后缀。 - 禁止磁盘绝对路径(如
C:/...)。 - 不要用
import/export。
