• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 静态方式加载Native模块
2<!--Kit: ArkTS-->
3<!--Subsystem: ArkCompiler-->
4<!--Owner: @yao_dashuai-->
5<!--Designer: @yao_dashuai-->
6<!--Tester: @kirl75; @zsw_zhushiwei-->
7<!--Adviser: @foryourself-->
8
9在ES6(ECMAScript 6.0)模块设计中,使用import语法加载其他文件导出的内容是ECMA规范所定义的语法规则。为支持开发者使用该功能导入Native模块(so)导出的内容,ArkTS进行了相关适配,并提供了以下几种支持写法。
10
11## 直接导入
12在Native模块的index.d.ts文件中导出,并在文件内直接导入。
13
14### 具名导入
15```ts
16// libentry.so对应的index.d.ts
17export const add: (a: number, b: number) => number;
18```
19```ts
20// test.ets
21import { add } from 'libentry.so'
22add(2, 3);
23```
24
25### 默认导入
26```ts
27// libentry.so对应的index.d.ts
28export const add: (a: number, b: number) => number;
29```
30```ts
31// test.ets
32import entry from 'libentry.so'
33entry.add(2, 3);
34```
35
36### 命名空间导入
37```ts
38// libentry.so对应的index.d.ts
39export const add: (a: number, b: number) => number;
40```
41```ts
42// test.ets
43import * as entry from 'libentry.so'
44entry.add(2, 3);
45```
46
47## 间接导入
48
49### 转为具名变量导出再导入
50```ts
51// libentry.so对应的index.d.ts
52export const add: (a: number, b: number) => number;
53```
54```ts
55// test1.ets
56// 将libentry.so的API封装后导出
57import { add } from 'libentry.so';
58export { add };
59```
60```ts
61// test2.ets
62// 从中间模块导入API
63import { add } from './test1';
64const result = add(2, 3);
65```
66
67### 转为命名空间导出再导入
68```ts
69// libentry.so对应的index.d.ts
70export const add: (a: number, b: number) => number;
71```
72```ts
73// test1.ets
74export * from 'libentry.so'
75```
76```ts
77// test2.ets
78import { add } from './test1'
79add(2, 3);
80```
81> **注意:**
82>
83> 不支持Native模块导出和导入同时使用命名空间。
84
85**反例:**
86```ts
87// test1.ets
88export * from 'libentry.so'
89```
90```ts
91// test2.ets
92import * as add from './test1'
93// 无法获取add对象
94```
95
96## 动态导入
97
98### 直接导入
99```ts
100// libentry.so对应的index.d.ts
101export const add: (a: number, b: number) => number;
102```
103```ts
104// test.ets
105import('libentry.so').then((entry:ESObject) => {
106    entry.default.add(2, 3);
107})
108```
109### 间接导入
110```ts
111// test1.ets
112import entry from 'libentry.so'
113export { entry }
114
115// test2.ets
116import('./test1').then((ns:ESObject) => {
117    ns.entry.add(2, 3);
118})
119```
120
121> **注意:**
122>
123> 不支持动态加载时,导出文件使用命名空间。
124
125**反例:**
126```ts
127// test1.ets
128export * from 'libentry.so'
129```
130```ts
131// test2.ets
132import('./test1').then((ns:ESObject) => {
133    // 无法获取ns对象
134})
135```