• 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**: Native modules do not support both export and import using namespaces simultaneously.
72**Anti-example:**
73```ts
74// test1.ets
75export * from 'libentry.so'
76```
77```ts
78// test2.ets
79import * as add from 'file1'
80// The add object cannot be obtained.
81```
82
83## Dynamic Import
84
85### Direct Import
86```ts
87// index.d.ts corresponding to libentry.so
88export const add: (a: number, b: number) => number;
89```
90```ts
91// test.ets
92import('libentry.so').then((ns:ESObject) => {
93    ns.default.add(2, 3);
94})
95```
96### Indirect Import
97```ts
98// test1.ets
99import add from 'libentry.so'
100export { add }
101
102// test2.ets
103import('./test1').then((ns:ESObject) => {
104    ns.add.add(2, 3);
105})
106```
107
108**Note**: Dynamic imports do not support exporting files using namespace exports.
109**Anti-example:**
110```ts
111// test1.ets
112export * from 'libentry.so'
113```
114```ts
115// test2.ets
116import('./test1').then((ns:ESObject) => {
117    // The ns object cannot be obtained.
118})
119```
120