Skip to content

模块与 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.jsrequire('../common/hello.js')
pages/home/page.js → common/hello.jsrequire('../../common/hello.js')
pages/home/page.js → 同目录 helperrequire('./helper.js')
tasks/a.js → tasks/b.jsrequire('./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。