In 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:
Export content from the index.d.ts file of a native module, and then import the content to the file.
// index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
// NameImport.ets
import { add } from 'libentry.so'
add(2, 3); // index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
// DefaultImport.ets import entry from 'libentry.so' entry.add(2, 3);
// index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
// NamespaceImport.ets import * as entry from 'libentry.so' entry.add(2, 3);
// index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
// NameExport.ets
// Encapsulate the API of libentry.so and export it.
import { add } from 'libentry.so';
export { add }; // NameImportFromExport.ets
// Import APIs from the intermediate module.
import { add } from './NameExport';
const result = add(2, 3); // index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
// NamespaceExport.ets export * from 'libentry.so'
// NamespaceImportFromExport.ets
import { add } from './NamespaceExport'
add(2, 3);
Native modules do not support both export and import using namespaces simultaneously.
Anti-example:
// test1.ets export * from 'libentry.so'
// test2.ets import * as add from './test1' // The add object cannot be obtained.
// index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
// DynamicImport.ets
import('libentry.so').then((entry:ESObject) => {
entry.default.add(2, 3);
}) // DynamicExport.ets
import entry from 'libentry.so'
export { entry } // DynamicImportFromExport.ets
import('./DynamicExport').then((ns:ESObject) => {
ns.entry.add(2, 3);
})
Dynamic imports do not support exporting files using namespace exports.
Anti-example:
// test1.ets export * from 'libentry.so'
// test2.ets
import('./test1').then((ns:ESObject) => {
// The ns object cannot be obtained.
})