本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新
一、依赖管理问题
1. 依赖冲突
问题现象:
- 编译时报
Duplicate class
错误 - 运行时出现
NoSuchMethodError
解决:
# 1. 查看依赖树
ohpm list --depth=3
# 2. 在oh-package.json5中强制指定版本
"resolutions": {
"package-a/conflict-package": "1.2.0"
}
# 3. 使用exclude排除冲突包
"dependencies": {
"package-a": {
"version": "1.0.0",
"exclude": ["conflict-package"]
}
}
2. 版本不兼容
问题现象:
- API调用报错
undefined is not a function
- 组件渲染异常
解决:
# 查看包支持的API版本
ohpm info package-name --versions
# 安装指定版本
ohpm install package-name@7.0.0
二、功能兼容性
1. 鸿蒙API适配问题
问题现象:
- 调用三方包方法返回
Not supported
错误 - 功能表现与文档不符
解决:
// 1. 使用条件编译
import abilityFeature from '@ohos.ability.featureAbility';
const isHarmonyOS = typeof abilityFeature !== 'undefined';
if (isHarmonyOS) {
// 鸿蒙专用实现
} else {
// 备用实现
}
// 2. 封装适配层
class LocationAdapter {
static getLocation() {
return ohpmPackage.getLocation()
.catch(() => nativeHarmonyLocationAPI());
}
}
三、性能问题
1. 启动耗时增加
问题现象:
- 应用启动时间明显变长
- 首屏渲染延迟
解决:
// oh-package.json5配置
{
"optimization": {
"treeShaking": true,
"codeSplitting": {
"routes": ["/main", "/settings"]
}
}
}
2. 内存泄漏
问题现象:
- 内存占用持续增长
- 频繁GC导致卡顿
解决:
// 1. 及时释放资源
class CameraService {
private camera: ohpm.Camera;
release() {
this.camera?.stopPreview();
this.camera?.release();
}
}
// 2. 使用WeakRef
const cache = new Map<number, WeakRef<Image>>();
function getImage(id: number): Image | null {
const ref = cache.get(id);
return ref?.deref() || null;
}