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