1# 同步方式动态加载Native模块 2<!--Kit: ArkTS--> 3<!--Subsystem: ArkCompiler--> 4<!--Owner: @shilei123--> 5<!--Designer: @yao_dashuai--> 6<!--Tester: @kirl75; @zsw_zhushiwei--> 7<!--Adviser: @foryourself--> 8 9[loadNativeModule接口](../reference/common/js-apis-common-load-native-module.md)用于同步动态加载Native模块,目的是按需加载所需要的模块。使用该接口会增加加载so文件的时间,开发者需评估其对功能的影响。 10 11## 函数说明 12 13```js 14loadNativeModule(moduleName: string): Object; 15``` 16 17| 参数 | 说明 | 18| :------------- | :----------------------------- | 19| moduleName | 加载的模块名。 | 20 21> **说明** 22> loadNativeModule加载的模块名是指依赖方oh-package.json5文件的dependencies中的名字。 23> 24> loadNativeModule必须在UI主线程中调用。 25> 26> 该接口在加载常量字符串或变量表达式作为参数时,需要配置依赖。 27 28## loadNativeModule支持的场景 29 30| 场景 | 示例 | 31| :------------- | :----------------------------- | 32| 系统库模块 | 加载@ohos.或@system. | 33| 应用内Native模块 | 加载libNativeLibrary.so | 34 35## 使用示例 36 37- **HAP加载系统库模块** 38 39```js 40let hilog: ESObject = loadNativeModule("@ohos.hilog"); 41hilog.info(0, "testTag", "loadNativeModule ohos.hilog success"); 42``` 43 44- **HAP加载Native库** 45 46libentry.so的index.d.ts文件如下: 47 48```javascript 49//index.d.ts 50export const add: (a: number, b: number) => number; 51``` 52 531.加载本地so库时,需要在oh-package.json5文件中配置dependencies项。 54 55```json 56{ 57 "dependencies": { 58 "libentry.so": "file:./src/main/cpp/types/libentry" 59 } 60} 61``` 62 632.在build-profile.json5中进行配置。 64 65```json 66{ 67 "buildOption": { 68 "arkOptions": { 69 "runtimeOnly": { 70 "packages": [ 71 "libentry.so" 72 ] 73 } 74 } 75 } 76} 77``` 78 793.使用loadNativeModule加载libentry.so,并调用add函数。 80 81```js 82let module: ESObject = loadNativeModule("libentry.so"); 83let sum: number = module.add(1, 2); 84``` 85