1# import native模块 2 3在ES6(ECMAScript6.0)模块设计中,社区使用import语法加载其他文件导出的内容(ECMA规范定义语法规格)。 4为支持开发者便捷使用该功能导入native模块(so)导出的内容,ArkTS进行相关适配,并给出以下几种支持写法。 5 6## 直接导入 7在native模块的index.d.ts文件中导出,在文件内直接导入。 8 9### 具名导入 10```ts 11// libentry.so对应的index.d.ts 12export const add: (a: number, b: number) => number; 13``` 14```ts 15// test.ets 16import { add } from 'libentry.so' 17add(2, 3); 18``` 19 20### 默认导入 21```ts 22// libentry.so对应的index.d.ts 23export const add: (a: number, b: number) => number; 24``` 25```ts 26// test.ets 27import add from 'libentry.so' 28add.add(2, 3); 29``` 30 31### 命名空间导入 32```ts 33// libentry.so对应的index.d.ts 34export const add: (a: number, b: number) => number; 35``` 36```ts 37// test.ets 38import * as add from 'libentry.so' 39add.add(2, 3); 40``` 41 42## 间接导入 43 44### 转为具名变量导出再导入 45```ts 46// test1.ets 47import hilog from '@ohos.hilog' 48export { hilog } 49``` 50```ts 51// test2.ets 52import { hilog } from './test1' 53hilog.info(0x000, 'testTag', '%{public}s', 'test'); 54``` 55 56### 转为命名空间导出再导入 57```ts 58// libentry.so对应的index.d.ts 59export const add: (a: number, b: number) => number; 60``` 61```ts 62// test1.ets 63export * from 'libentry.so' 64``` 65```ts 66// test2.ets 67import { add } from './test1' 68add(2, 3); 69``` 70**注意:** 不支持native模块导出和导入同时使用命名空间。 71**反例:** 72```ts 73// test1.ets 74export * from 'libentry.so' 75``` 76```ts 77// test2.ets 78import * as add from 'file1' 79// 无法获取add对象 80``` 81 82## 动态导入 83 84### 直接导入 85```ts 86// libentry.so对应的index.d.ts 87export const add: (a: number, b: number) => number; 88``` 89```ts 90// test.ets 91import('libentry.so').then((ns:ESObject) => { 92 ns.default.add(2, 3); 93}) 94``` 95### 间接导入 96```ts 97// test1.ets 98import add from 'libentry.so' 99export { add } 100 101// test2.ets 102import('./test1').then((ns:ESObject) => { 103 ns.add.add(2, 3); 104}) 105``` 106 107**注意:** 不支持动态加载时,导出文件使用命名空间导出。 108**反例:** 109```ts 110// test1.ets 111export * from 'libentry.so' 112``` 113```ts 114// test2.ets 115import('./test1').then((ns:ESObject) => { 116 // 无法获取ns对象 117}) 118```