Skip to content

require

会写 page.js 之后,可以把重复代码拆到公共文件。page.js 和自动化脚本都可以 require

路径有两种,不要拼磁盘绝对路径(开发时在工程目录,打包后在应用内部,根目录不同)。

写法基准示例
./../当前这个 JS 文件所在目录require('./helper.js')require('../../common/line.js')
不以 ./../ 开头项目根目录require('common/hello.js')require('tasks/sample.js')

被引入的文件用 module.exports 导出:

javascript
// common/hello.js
module.exports = {
  text: '你好,这是示例'
};
javascript
// pages/home/page.js
let hello = require('common/hello.js');
let helper = require('./helper.js');

Page({
  data: {
    hello: helper.greet('体验者'),
    hint: hello.runHint
  }
});

任务脚本同样可以 require 公共代码:

javascript
// tasks/follow.js
let hello = require('common/hello.js');
System.toast(hello.text);

完整规则见 模块

AutoJS文档 Released under the ISC License.