动态加载适用场景
动态加载可用于代替静态导入。动态加载可减少内存使用,实现异步获取,提高加载速度等
代码实现
需要导入的对象案例
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)
]
}
}
},
...