在HarmonyOS中,静态库(通常以.har为文件扩展名)是一种用于代码和资源共享的机制。它允许开发者创建可重用的组件、接口和资源,以便在多个应用中共享和复用。
@Component
export struct BasePage {
@State message: string = '';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
定义基础的类:
@Component
export class BaseConfig {
IMAGE_BACK_SIZE: number = 21;
IMAGE_BACK_MARGIN_RIGHT: number = 18;
IMAGE_LOADING_SIZE: number = 22;
BAR_HEIGHT: number = 47;
BAR_MARGIN_HORIZONTAL: number = 26;
BAR_MARGIN_TOP: number = 10;
WEIGHT: string = '50%';
}
2.导出内容
在ets文件夹下的index.ets文件中,使用export关键字导出你想要共享的组件或接口。如下示例,导出一个页面和一个名为 BaseConfig 的类。
export { MainPage } from './src/main/ets/components/mainpage/MainPage'
export { DKBaseBleAlg } from './src/main/ets/components/DKBaseBleAlg'
2.获取.har文件
编译成功后,在模块的build/default/outputs/default目录下找到baselibrary.har文件。
{
"license": "",
"devDependencies": {},
"author": "",
"name": "entry",
"description": "Please describe the basic information.",
"main": "",
"version": "1.0.0",
"dependencies": {
// 直接使用module,直接引用module的路径
"Baselibrary": "file:../Baselibrary"
// 将wmdinglibrary.har放到固定目录下时引用
// "Baselibrary": "file:../entry/src/main/lib/Baselibrary.har"
}
}
import { Baselibrary, MainPage } from 'Baselibrary'
@Entry
@Component
struct UseLibraryPage {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
解决措施
HarmonyOS library引用本地的har包的引用方式需要进行改造,具体步骤为: