往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)
静态方式加载native模块
在ES6(ECMAScript6.0)模块设计中,社区使用import语法加载其他文件导出的内容(ECMA规范定义语法规格)。
为支持开发者使用该功能导入native模块(so)导出的内容,ArkTS进行了相关适配,并提供了以下几种支持写法。
直接导入
在native模块的index.d.ts文件中导出,在文件内直接导入。
具名导入
// libentry.so对应的index.d.ts
export const add: (a: number, b: number) => number;
// test.ets
import { add } from 'libentry.so'
add(2, 3);
默认导入
// libentry.so对应的index.d.ts
export const add: (a: number, b: number) => number;
// test.ets
import entry from 'libentry.so'
entry.add(2, 3);
命名空间导入
// libentry.so对应的index.d.ts
export const add: (a: number, b: number) => number;
// test.ets
import * as add from 'libentry.so'
add.add(2, 3);
间接导入
转为具名变量导出再导入
// test1.ets
import hilog from '@ohos.hilog'
export { hilog }
// test2.ets
import { hilog } from './test1'
hilog.info(0x000, 'testTag', '%{public}s', 'test');
转为命名空间导出再导入
// libentry.so对应的index.d.ts
export const add: (a: number, b: number) => number;
// test1.ets
export * from 'libentry.so'
// test2.ets
import { add } from './test1'
add(2, 3);
注意
不支持native模块导出和导入同时使用命名空间。
反例:
// test1.ets
export * from 'libentry.so'
// test2.ets
import * as add from 'file1'
// 无法获取add对象
动态导入
直接导入
// libentry.so对应的index.d.ts
export const add: (a: number, b: number) => number;
// test.ets
import('libentry.so').then((ns:ESObject) => {
ns.default.add(2, 3);
})
间接导入
// test1.ets
import add from 'libentry.so'
export { add }
// test2.ets
import('./test1').then((ns:ESObject) => {
ns.add.add(2, 3);
})
注意
不支持动态加载时,导出文件使用命名空间导出。
反例:
// test1.ets
export * from 'libentry.so'
// test2.ets
import('./test1').then((ns:ESObject) => {
// 无法获取ns对象
})