• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Statically Loading Native Modules
2
3In ECMAScript 6.0 (ES6) module design, the **import** syntax is used to load content exported by other files, as defined by the ECMAScript specification. To help you import content exported from native modules (.so), ArkTS has adapted and provides the following methods:
4
5## Direct Import
6Export content from the **index.d.ts** file of a native module, and then import the content to the file.
7
8### Named Import
9```ts
10// index.d.ts corresponding to libentry.so
11export const add: (a: number, b: number) => number;
12```
13```ts
14// test.ets
15import { add } from 'libentry.so'
16add(2, 3);
17```
18
19### Default Import
20```ts
21// index.d.ts corresponding to libentry.so
22export const add: (a: number, b: number) => number;
23```
24```ts
25// test.ets
26import entry from 'libentry.so'
27entry.add(2, 3);
28```
29
30### Namespace Import
31```ts
32// index.d.ts corresponding to libentry.so
33export const add: (a: number, b: number) => number;
34```
35```ts
36// test.ets
37import * as add from 'libentry.so'
38add.add(2, 3);
39```
40
41## Indirect Import
42
43### Export as Named Variables and Import
44```ts
45// test1.ets
46import hilog from '@ohos.hilog'
47export { hilog }
48```
49```ts
50// test2.ets
51import { hilog } from './test1'
52hilog.info(0x000, 'testTag', '%{public}s', 'test');
53```
54
55### Export as Namespaces and Import
56```ts
57// index.d.ts corresponding to libentry.so
58export const add: (a: number, b: number) => number;
59```
60```ts
61// test1.ets
62export * from 'libentry.so'
63```
64```ts
65// test2.ets
66import { add } from './test1'
67add(2, 3);
68```
69> **NOTE**
70>
71> Native modules do not support both export and import using namespaces simultaneously.
72
73**Anti-example:**
74```ts
75// test1.ets
76export * from 'libentry.so'
77```
78```ts
79// test2.ets
80import * as add from './test1'
81// The add object cannot be obtained.
82```
83
84## Dynamic Import
85
86### Direct Import
87```ts
88// index.d.ts corresponding to libentry.so
89export const add: (a: number, b: number) => number;
90```
91```ts
92// test.ets
93import('libentry.so').then((ns:ESObject) => {
94    ns.default.add(2, 3);
95})
96```
97### Indirect Import
98```ts
99// test1.ets
100import add from 'libentry.so'
101export { add }
102
103// test2.ets
104import('./test1').then((ns:ESObject) => {
105    ns.add.add(2, 3);
106})
107```
108
109> **NOTE**
110>
111> Dynamic imports do not support exporting files using namespace exports.
112
113**Anti-example:**
114```ts
115// test1.ets
116export * from 'libentry.so'
117```
118```ts
119// test2.ets
120import('./test1').then((ns:ESObject) => {
121    // The ns object cannot be obtained.
122})
123```
124