存量RN项目支持HarmonyOS NEXT
RN工程React Native OpenHarmony化版本
当前React NativeOpenHarmony版本基于社区RN 0.72.5进行适配,如果现有RN项目使用的版本较低,条件允许的情况下需要考虑RN和依赖库的版本升降级改造。
配置package.json
生成bundle命令:"dev": "react-native bundle-harmony --dev"添加OpenHarmonyRN依赖:"@react-native-oh/react-native-harmony": "^0.72.53-1"
修改配置文件
metro.config.js合并OpenHarmony配置项
// metro.config.js
const { mergeConfig, getDefaultConfig } = require('@react-native/metro-config');
const {
createHarmonyMetroConfig,
} = require('@react-native-oh/react-native-harmony/metro.config');
// 项目原有配置
const config = {
******
};
module.exports = mergeConfig(
getDefaultConfig(__dirname),
createHarmonyMetroConfig({
reactNativeHarmonyPackageName: '@react-native-oh/react-native-harmony',
}),
config
);
参考:创建React Native工程
鸿蒙原生工程
跟着官方文档操作,主要看用哪种加载bundle方式:Metro:使用MetroJSBundleProvider,启动Metro服务推bundle;资源文件:FileJSBundleProvider,读沙箱文件;ResourceJSBundleProvider,读rawfile。
参考:创建鸿蒙工程
RN三方库
openharmony RN项目三方库
RN项目需要针对每一个三方库进行处理,这块要仔细操作,根据官方文档中的三方库对照表,逐个根据文档处理。各个库的处理工作不同,通常下列这些:●RN工程中安装OpenHarmony版的库;●RN工程安装OpenHarmony版的库后,从node_modules对应库的路径下取har包,放到OpenHarmony工程中安装;●OpenHarmony工程安装har包,把oh_modules对应库的cpp路径到CMakeList.txt构建●使用codegen生成代码,generated目录放入OpenHarmony工程,添加到CMakeList.txt构建
自定义TurboModule
一般我们存量的RN工程中都有用到自定义TurboModule,这块需要RN工程适配OpenHarmony改造,和原生工程代码实现。
RN工程
自定义的TurboModule模块的package.json中添加harmony配置
{
"harmony": {
"alias": "xxx",
"codegenConfig": [
{
"version": 1,
"specPaths": [
"xxx"
]
}
]
},
}RN工程的package.json配置codegen:
"scripts": {
···
"codegen": "react-native codegen-harmony --cpp-output-path ./entry/src/main/cpp/generated --rnoh-module-path ./entry/oh_modules/@rnoh/react-native-openharmony"
}执行生成胶水代码
原生工程
1、上面生成的胶水代码拷贝到原生工程。
2、继承TurboModule定义接口实现类。
3、继承TurboModuleFactory定义TurboModule工厂类;继承RNPackage定义自定义RNPackage类使用TurboModule工厂类;自定义的RNPackage类加入到createRNPackages方法的返回数组中。
参考:TurboModule
页:
[1]