鸿蒙ArkTS中动态加载

动态加载适用场景

动态加载可用于代替静态导入。动态加载可减少内存使用,实现异步获取,提高加载速度等

代码实现

需要导入的对象案例

export class MyUtils {
  //静态成员函数
  public static staticAdd2(a: number, b: number): number {
    return a + b;
  }

  //成员函数
  public instanceAdd2(a: number, b: number): number {
    return a + b;
  }
}

//全局函数
export function commonHarAdd2(a: number, b: number): number {
  return a + b;
}

//如果是跨包加载,还需要在index.ets下导出class和全局函数

静态加载案例

import {MyUtils} from 'common'

...
MyUtils.staticAdd2(1,2)

动态加载案例

import('common').then((ns: ESObject) => {
  ns.MyUtils.staticAdd2(1, 2) // 调用静态成员函数staticAdd2()
  let myUtils: ESObject = new ns.MyUtils() // 实例化类MyUtils
  myUtils.instanceAdd2(10, 11) // 调用成员函数instanceAdd2()
  ns.commonHarAdd2(6, 7) // 调用全局方法commonHarAdd2()

  // 使用类、成员函数和方法的字符串名字进行反射调用
  let className = 'MyUtils'
  let methodName = 'instanceAdd2'
  let staticMethod = 'staticAdd2'
  let functionName = 'commonHarAdd2'
  ns[className][staticMethod](12, 13) // 调用静态成员函数staticAdd2()
  let myUtils2: ESObject = new ns[className]() // 实例化类MyUtils
  myUtils2[methodName](14, 15) // 调用成员函数instanceAdd2()
  ns[functionName](16, 17) // 调用全局方法commonHarAdd2()
})

使用变量动态导入

此外还存在import其他模块的情况,即import中传入的不是字符串而是变量

let harName = 'myHar';
import(harName).then(……)

 需要在导入模块中进行额外配置(HAR1变量动态导入common,需要在HAR1中增加额外配置)

//build-profile.json5
...
"buildOption": {
    "arkOptions": {
      "runtimeOnly": {
        "packages": [
          "common"
          //目标为其他包下的文件,需要在package中配置,且要求与dependencies中配置的名字一致
        ],
        "sources": [
          "./src/main/ets/utils/MyUtils.ets"
          //目标为当前包下的文件,则增加相对路径(相对于build-profile.json5)
        ]
      }
    }
  },
...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值