首先理解一下什么是模块化:
模块化设计:应用被分解为多个功能模块,其中每个模块负责执行特定的功能。通过模块化设计提高了代码的可理解性和可复用性,使应用的扩展和维护变得更为简便,同时降低了系统各部分之间的耦合度。
就是"业务框架"或者“业务模块",也可以理解为“框架”,意思是把功能进行划分,将同一类型的代码整合在一起,所以模块的功能相对复杂,但都同属于一个业务。
使用场景:按照项目功能需求划分成不同类型的业务框架(例如:注册、登录、外卖、直播…)
那么我们如何实现harmonyos的模块化那:
我的环境:
deveco studio 4.0
api9
一、新建module
在你的项目中新建module,选择shared library,static library,visual library三种template中的一种:
这三种module有什么不同那:
- VisualLibrary 是低代码开发库,使用视图拖拽生成界面
- SharedLibrary 就是 HSP(Harmony Shared Package)动态共享包
- StaticLibrary 是HAR(Harmony Archive)静态共享包
HarmonyOS提供了两种共享包,HAR(Harmony Archive)静态共享包,和HSP(Harmony Shared Package)动态共享包。
HAR与HSP都是为了实现代码和资源的共享,都可以包含代码、C++库、资源和配置文件,最大的不同之处在于:HAR中的代码和资源跟随使用方编译,如果有多个使用方,它们的编译产物中会存在多份相同拷贝;而HSP中的代码和资源可以独立编译,运行时在一个进程中代码也只会存在一份。
图1 HAR和HSP在APP包中的形态示意图
HSP旨在解决HAR存在的几个问题:
- 多个HAP引用相同的HAR,导致的APP包大小膨胀问题。
- 多个HAP引用相同的HAR,HAR中的一些状态变量无法共享的问题。
HSP的一些约束:
- HSP及其使用方都必须是Stage模型。
- HSP及其使用方都必须使用esmodule编译模式。
- HSP不支持在配置文件中声明abilities、extensionAbilities标签。
HSP按照使用场景可以分为应用内HSP和应用间HSP,应用间HSP暂不支持。
二、module 中的类对外暴露export
调用起来还是很简单的,感觉比安卓简单,我们就以staticlibary,写一个log工具为例:
目录结构:
Logger,写一个工具类,然后通过export 暴露一个实例化对象:
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import hilog from '@ohos.hilog';
/**
* 日志打印类
*/
class Logger {
private domain: number;
private prefix: string;
private format: string = '%{public}s, %{public}s';
constructor(prefix: string) {
this.prefix = prefix;
this.domain = 0xFF00;
this.format.toUpperCase();
}
debug(...args: string[]) {
hilog.debug(this.domain, this.prefix, this.format, args);
}
info(...args: string[]) {
hilog.info(this.domain, this.prefix, this.format, args);
}
warn(...args: string[]) {
hilog.warn(this.domain, this.prefix, this.format, args);
}
error(...args: string[]) {
hilog.error(this.domain, this.prefix, this.format, args);
}
}
export let logger = new Logger('[CommonAppDevelopment]')
在Index.ets中通过路径把对象暴露出去,当然也是export:
export { logger } from './src/main/ets/components/log/Logger'
三、导入module
导入module需要在要使用的nodule中的oh-package.json5文件中配置声明路径,在dependencies中键值对的形式进行配置,key键是你在本项目中应用的路径声明,value是要引入模块的路径:
路径错误会如下显示:
对的情况是:
对了之后点击红灯泡,当然你也可以自己去敲,本人是非常懒的:
安装成功后的效果:
四、使用
导入成功后,在具体的地方应用:
引入方式用import {对外暴露的名称} from "在oh-package.json5配置的key名"
import {logger} from '@ohos/base';
像正常内部类调用就行:
logger.info("aboutToAppear");