1# 静态方式加载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 entry from 'libentry.so' 28entry.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> **注意:** 71> 72> 不支持native模块导出和导入同时使用命名空间。 73 74**反例:** 75```ts 76// test1.ets 77export * from 'libentry.so' 78``` 79```ts 80// test2.ets 81import * as add from 'file1' 82// 无法获取add对象 83``` 84 85## 动态导入 86 87### 直接导入 88```ts 89// libentry.so对应的index.d.ts 90export const add: (a: number, b: number) => number; 91``` 92```ts 93// test.ets 94import('libentry.so').then((ns:ESObject) => { 95 ns.default.add(2, 3); 96}) 97``` 98### 间接导入 99```ts 100// test1.ets 101import add from 'libentry.so' 102export { add } 103 104// test2.ets 105import('./test1').then((ns:ESObject) => { 106 ns.add.add(2, 3); 107}) 108``` 109 110> **注意:** 111> 112> 不支持动态加载时,导出文件使用命名空间导出。 113 114**反例:** 115```ts 116// test1.ets 117export * from 'libentry.so' 118``` 119```ts 120// test2.ets 121import('./test1').then((ns:ESObject) => { 122 // 无法获取ns对象 123}) 124```