#三方框架# #React Native #
1 。環境配置;
安裝 DevEco 開發工具;
Node 版本16+;
hdc環境配置
hdc 是 OpenHarmony 為開發人員提供的用于調試的命令行工具,鴻蒙 React Native 工程使用 hdc 進行真機調試。hdc 工具通過 OpenHarmony SDK 獲取,存放于 SDK 的?toolchains
?目錄下,請將?{DevEco Studio安裝路徑}/sdk/{SDK版本}/openharmony/toolchains
?的完整路徑添加到環境變量中。
安裝 DevEco 的時候 勾選一下。就不用單獨的添加環境變量了 。
配置 CAPI 版本環境變量
當前RN框架提供的 Demo 工程默認為 CAPI 版本,您需要配置環境變量?RNOH_C_API_ARCH = 1
。
-
Windows 環境:
在此電腦 > 屬性 > 高級系統設置 > 高級 > 環境變量中,在系統變量中點擊新建,添加變量名為:
RNOH_C_API_ARCH
,變量值為?1
。
2,創建RN 工程
使用 React Native 內置的命令行工具來創建一個名為 “AwesomeProject” 的新項目。這個命令行工具不需要安裝,可以直接用 node 自帶的 npx 命令來創建,目前 React Native for OpenHarmony 僅支持?0.72.5?版本的 React Native:
npx react-native@0.72.5 init AwesomeProject --version 0.72.5
?該命令在 mac 環境下初始化 React Native 項目時會下載 iOS 依賴庫,耗時較長,開發者可以選擇執行以下命令跳過該過程,后續根據需要自行下載,不影響鴻蒙項目開發:
npx react-native@0.72.5 init AwesomeProject --version 0.72.5 --skip-install
安裝鴻蒙化依賴
-
打開?
AwesomeProject
?目錄下的?package.json
,在?scripts
?下新增 OpenHarmony 的依賴:{"name": "AwesomeProject","version": "0.0.1","private": true,"scripts": {"android": "react-native run-android","ios": "react-native run-ios","lint": "eslint .","start": "react-native start","test": "jest", + "dev": "react-native bundle-harmony --dev"},"dependencies": {"react": "18.2.0","react-native": "0.72.5"},"devDependencies": {"@babel/core": "^7.20.0","@babel/preset-env": "^7.20.0","@babel/runtime": "^7.20.0","@react-native/eslint-config": "^0.72.2","@react-native/metro-config": "^0.72.11","@tsconfig/react-native": "^3.0.0","@types/react": "^18.0.24","@types/react-test-renderer": "^18.0.0","babel-jest": "^29.2.1","eslint": "^8.19.0","jest": "^29.2.1","metro-react-native-babel-preset": "0.76.8","prettier": "^2.4.1","react-test-renderer": "18.2.0","typescript": "4.8.4"},"engines": {"node": ">=16"} }
-
在?
AwesomeProject
?目錄下運行安裝依賴包命令:npm i @react-native-oh/react-native-harmony@x.x.x
注意:
- 指令中@x.x.x用于指定下載的版本,不指定時默認下載最新版本。
- 本地安裝鴻蒙化依賴,請參考如何使用本地安裝鴻蒙化依賴。
- 如何從本地依賴切換至遠程依賴,請參考如何從本地依賴切換至遠程依賴。
生成bundle
-
打開?
AwsomeProject\metro.config.js
,并添加 OpenHarmony 的適配代碼。配置文件的詳細介紹,可以參考React Native 中文網。修改完成后的文件內容如下:const {mergeConfig, getDefaultConfig} = require('@react-native/metro-config'); const {createHarmonyMetroConfig} = require('@react-native-oh/react-native-harmony/metro.config');/** * @type {import("metro-config").ConfigT} */ const config = {transformer: {getTransformOptions: async () => ({transform: {experimentalImportSupport: false,inlineRequires: true,},}),}, };module.exports = mergeConfig(getDefaultConfig(__dirname), createHarmonyMetroConfig({reactNativeHarmonyPackageName: '@react-native-oh/react-native-harmony', }), config);
-
在 AwesomeProject 目錄下運行生成 bundle 文件的命令。運行成功后,會在?
AwesomeProject/harmony/entry/src/main/resources/rawfile
?目錄下生成?bundle.harmony.js
?和?assets
?文件夾,assets
?用來存放圖片(如果?bundle
?中不涉及本地圖片,則沒有?assets
?文件夾)。npm run dev
成功之后可以看到如下內容:
創建鴻蒙工程
本章節主要介紹了鴻蒙工程的創建,并加載 React Native 相關的依賴包和 bundle 包,最終完成鴻蒙工程的運行的過程。
您可以按照本節中的操作一步一步完成環境的搭建,也可以使用附件中的?
MyApplicationReplace.zip
?的內容,一一替換對應的文件,修改版本并運行。
新建工程或者在已有工程中集成
? 下面演示在新建工程中集成。點擊?File > New > Create Project
,選擇創建?Empty Ability
?工程,如圖所示:
? 點擊?Next
?按鈕,并在?Compile SDK
?中選擇?API13
,(為了防止最新版本有各種問題)創建一個名為 “MyApplication” 的項目。注意項目路徑不要太長,如圖所示:
? 連接真機,點擊?File > Project Structure
,在彈窗界面點擊?Signing Configs
,勾選?Support HarmonyOS
?和?Automatically generate signature
,然后點擊?Sign In
?登錄華為賬號,并簽名。
添加 React Native 配置
在?entry
?目錄下執行以下命令:
ohpm i @rnoh/react-native-openharmony@x.x.x
執行完成后會在工程級目錄以及模塊級目錄下生成?oh_modules
?文件夾。
注意:
- 指令中@x.x.x用于指定下載的版本,不指定時默認下載最新版本。
- 由于 har 包比較大,這一步耗時會比較長,務必保證?
ohpm install
?和 IDE 自發的?SyncData
?全都完成,否則會導致編譯報錯。- 如何在三方庫或自定義module中引入rnoh的依賴,請參考文檔。
在原生工程中集成RNOH
補充CPP側代碼
- 在?
MyApplication/entry/src/main
?目錄下新建 cpp 文件夾。 - 在 cpp 目錄下新增?
CMakeLists.txt
,并將?RNOH?的適配層代碼添加到編譯構建中生成?librnoh_app.so
:project(rnapp) cmake_minimum_required(VERSION 3.4.1) set(CMAKE_SKIP_BUILD_RPATH TRUE) set(OH_MODULE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules") set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")set(RNOH_CPP_DIR "${OH_MODULE_DIR}/@rnoh/react-native-openharmony/src/main/cpp") set(RNOH_GENERATED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/generated") set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments") set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie") add_compile_definitions(WITH_HITRACE_SYSTRACE) set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to useadd_subdirectory("${RNOH_CPP_DIR}" ./rn)add_library(rnoh_app SHARED"./PackageProvider.cpp""${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp" )target_link_libraries(rnoh_app PUBLIC rnoh)
- 在 cpp 目錄下新增?
PackageProvider.cpp
,該文件需要滿足以下要求:- 需要導入?
RNOH/PackageProvider
; - 實現?
getPackages
?方法,用于創建三方庫或自定義 TurboModule 或 Fabric 的 package 對象。
此處不涉及三方庫與自定義 TurboModule 或組件,需要返回空數組。
#include "RNOH/PackageProvider.h"using namespace rnoh;std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {return {}; }
- 需要導入?
- 打開?
MyApplicaton\entry\build-profile.json5
,將 cpp 中的代碼添加到鴻蒙的編譯構建任務中,詳細介紹可以參考模塊級build-profile.json5:{"apiType": "stageMode","buildOption": { + "externalNativeOptions": { + "path": "./src/main/cpp/CMakeLists.txt", + "arguments": "", + "cppFlags": "", + }},"buildOptionSet": [{"name": "release","arkOptions": {"obfuscation": {"ruleOptions": {"enable": true,"files": ["./obfuscation-rules.txt"]}}}},],"targets": [{"name": "default"},{"name": "ohosTest",}] }
補充ArkTS側的代碼
- 打開?
MyApplicaton\entry\src\main\ets\entryability\EntryAbility.ets
,引入并使用?RNAbility
,該文件需要滿足以下的要求:- 如果需要擴展使用對應的生命周期函數,請在代碼中使用 super,
RNAbility
?在生命周期函數中進行了對應的操作,需要使用 super 保證功能不丟失; - 需要重寫?
getPagePath
,返回程序的入口 page。
import { RNAbility } from '@rnoh/react-native-openharmony';export default class EntryAbility extends RNAbility {getPagePath() {return 'pages/Index';} }
- 如果需要擴展使用對應的生命周期函數,請在代碼中使用 super,
- 在?
MyApplicaton\entry\src\main\ets
?目錄下新增?RNPackagesFactory.ets
,該文件需要滿足以下要求:- 在?
@rnoh/react-native-openharmony
?導入?RNPackageContext
?和?RNPackage
; - 在文件中導出?
createRNPackages
?方法,用于創建三方庫或自定義 TurboModule、Fabric的package 對象。
此處不涉及三方庫與自定義TurboModule或組件,需要返回空數組。
import { RNPackageContext, RNPackage } from '@rnoh/react-native-openharmony/ts'; export function createRNPackages(ctx: RNPackageContext): RNPackage[] {return []; }
- 在?
- 打開?
MyApplicaton\entry\src\main\ets\pages\Index.ets
,添加RNOH的使用代碼,修改后如下:RNApp
的參數appKey
需要與RN工程中AppRegistry.registerComponent
注冊的appName
保持一致,否則會導致白屏。import {AnyJSBundleProvider,ComponentBuilderContext,FileJSBundleProvider,MetroJSBundleProvider,ResourceJSBundleProvider,RNApp,RNOHErrorDialog,RNOHLogger,TraceJSBundleProviderDecorator,RNOHCoreContext } from '@rnoh/react-native-openharmony'; import { createRNPackages } from '../RNPackagesFactory';@Builder export function buildCustomRNComponent(ctx: ComponentBuilderContext) {}const wrappedCustomRNComponentBuilder = wrapBuilder(buildCustomRNComponent)@Entry @Component struct Index {@StorageLink('RNOHCoreContext') private rnohCoreContext: RNOHCoreContext | undefined = undefined@State shouldShow: boolean = falseprivate logger!: RNOHLoggeraboutToAppear() {this.logger = this.rnohCoreContext!.logger.clone("Index")const stopTracing = this.logger.clone("aboutToAppear").startTracing();this.shouldShow = truestopTracing();}onBackPress(): boolean | undefined {// NOTE: this is required since `Ability`'s `onBackPressed` function always// terminates or puts the app in the background, but we want Ark to ignore it completely// when handled by RNthis.rnohCoreContext!.dispatchBackPress()return true}build() {Column() {if (this.rnohCoreContext && this.shouldShow) {if (this.rnohCoreContext?.isDebugModeEnabled) {RNOHErrorDialog({ ctx: this.rnohCoreContext })}RNApp({rnInstanceConfig: {createRNPackages,enableNDKTextMeasuring: true, // 該項必須為true,用于開啟NDK文本測算enableBackgroundExecutor: false,enableCAPIArchitecture: true, // 該項必須為true,用于開啟CAPIarkTsComponentNames: []},initialProps: { "foo": "bar" } as Record<string, string>,appKey: "AwesomeProject",wrappedCustomRNComponentBuilder: wrappedCustomRNComponentBuilder,onSetUp: (rnInstance) => {rnInstance.enableFeatureFlag("ENABLE_RN_INSTANCE_CLEAN_UP")},jsBundleProvider: new TraceJSBundleProviderDecorator(new AnyJSBundleProvider([new MetroJSBundleProvider(),// NOTE: to load the bundle from file, place it in// `/data/app/el2/100/base/com.rnoh.tester/files/bundle.harmony.js`// on your device. The path mismatch is due to app sandboxing on OpenHarmonynew FileJSBundleProvider('/data/storage/el2/base/files/bundle.harmony.js'),new ResourceJSBundleProvider(this.rnohCoreContext.uiAbilityContext.resourceManager, 'hermes_bundle.hbc'),new ResourceJSBundleProvider(this.rnohCoreContext.uiAbilityContext.resourceManager, 'bundle.harmony.js')]),this.rnohCoreContext.logger),})}}.height('100%').width('100%')} }
加載bundle包
? 在上一章節中已經完成了 bundle 文件的生成,接下來將它加載到 DevEco Studio 中以運行 MyApplication 項目。加載 bundle 有三種方式:
-
方式一:本地加載 bundle。將 bundle 文件和 assets 圖片放在?
entry/src/main/resources/rawfile
?路徑下,在?entry/src/main/ets/pages/Index.ets
?中使用。
官方文檔寫了3種方式。我用的第一種!
全量編譯 C++ 代碼耗時較長,請耐心等待。
報錯:
由于cpp 目錄錯誤導致。
"externalNativeOptions": {"path": "./src/main/cpp/CMakeLists.txt","arguments": "","cppFlags": "","abiFilters": ["x86_64","arm64-v8a"]}
運行出錯:
Error message:Couldn't create bindings between ETS and CPP. libRNOHApp is undefined.
Stacktrace:
SourceMap is not initialized yet
at RNOHError (entry|@rnoh/react-native-openharmony|0.72.27|src/main/ets/RNOH/RNOHError.ts:16:9)
at FatalRNOHError (entry|@rnoh/react-native-openharmony|0.72.27|src/main/ets/RNOH/RNOHError.ts:1:1)
at onInit (entry|@rnoh/react-native-openharmony|0.72.27|src/main/ets/RNOH/NapiBridge.js:12:25)
at create (entry|@rnoh/react-native-openharmony|0.72.27|src/main/ets/RNOH/RNInstancesCoordinator.ts:63:36)
at onCreate (entry|@rnoh/react-native-openharmony|0.72.27|src/main/ets/RNOH/RNAbility.ts:64:39)
始終沒有解決 。
最后降低了?@rnoh/react-native-openharmony": 本版。
從?@rnoh/react-native-openharmony@0.72.67 到?@rnoh/react-native-openharmony": "0.72.38"
最終運行通過。
release包使用
-
在?
MyApplication
?目錄下新建 libs 文件夾,將?react_native_openharmony-xxx-release.har
?放入該目錄。 -
打開?
MyApplication/entry
?下的?oh-package.json5
,替換 har 包的依賴為對應版本的 release 包:{"name": "entry","version": "1.0.0","description": "Please describe the basic information.","main": "","author": "","license": "","dependencies": { + "@rnoh/react-native-openharmony": "file:../libs/react_native_openharmony-xxx-release.har"} }
-
替換?
MyApplication\entry\src\main\cpp\CMakeLists.txt
?文件為以下代碼:project(rnapp) cmake_minimum_required(VERSION 3.4.1) set(CMAKE_SKIP_BUILD_RPATH TRUE) set(NATIVERENDER_ROOT_PATH "${CMAKE_CURRENT_SOURCE_DIR}") set(OH_MODULE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules") set(RNOH_CPP_DIR "${OH_MODULE_DIR}/@rnoh/react-native-openharmony/src/main/include") set(REACT_COMMON_PATCH_DIR "${RNOH_CPP_DIR}/patches/react_native_core")set(CMAKE_CXX_STANDARD 17) set(LOG_VERBOSITY_LEVEL 1) set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments") set(RNOH_GENERATED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/generated") set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie -DNDEBUG") set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use add_compile_definitions(WITH_HITRACE_SYSTRACE) # folly的編譯選項 set(folly_compile_options-DFOLLY_NO_CONFIG=1-DFOLLY_MOBILE=1-DFOLLY_USE_LIBCPP=1-DFOLLY_HAVE_RECVMMSG=1-DFOLLY_HAVE_PTHREAD=1-Wno-comma-Wno-shorten-64-to-32-Wno-documentation-faligned-new ) add_compile_options("-Wno-unused-command-line-argument") # 添加頭文件目錄 include_directories(${NATIVERENDER_ROOT_PATH}${RNOH_CPP_DIR}${REACT_COMMON_PATCH_DIR}${RNOH_CPP_DIR}/third-party/folly${RNOH_CPP_DIR}/third-party/rn/ReactCommon${RNOH_CPP_DIR}/third-party/rn/ReactCommon/react/nativemodule/core${RNOH_CPP_DIR}/third-party/rn/ReactCommon/jsi${RNOH_CPP_DIR}/third-party/rn/ReactCommon/callinvoker${RNOH_CPP_DIR}/third-party/boost/libs/utility/include${RNOH_CPP_DIR}/third-party/boost/libs/stacktrace/include${RNOH_CPP_DIR}/third-party/boost/libs/predef/include${RNOH_CPP_DIR}/third-party/boost/libs/array/include${RNOH_CPP_DIR}/third-party/boost/libs/throw_exception/include${RNOH_CPP_DIR}/third-party/boost/libs/config/include${RNOH_CPP_DIR}/third-party/boost/libs/core/include${RNOH_CPP_DIR}/third-party/boost/libs/preprocessor/include${RNOH_CPP_DIR}/third-party/double-conversion${RNOH_CPP_DIR}/third-party/rn/ReactCommon/react/renderer/graphics/platform/cxx${RNOH_CPP_DIR}/third-party/rn/ReactCommon/runtimeexecutor${RNOH_CPP_DIR}/third-party/glog/src${RNOH_CPP_DIR}/third-party/boost/libs/mpl/include${RNOH_CPP_DIR}/third-party/boost/libs/type_traits/include${RNOH_CPP_DIR}/third-party/rn/ReactCommon/yoga${RNOH_CPP_DIR}/third-party/boost/libs/intrusive/include${RNOH_CPP_DIR}/third-party/boost/libs/assert/include${RNOH_CPP_DIR}/third-party/boost/libs/move/include${RNOH_CPP_DIR}/third-party/boost/libs/static_assert/include${RNOH_CPP_DIR}/third-party/boost/libs/container_hash/include${RNOH_CPP_DIR}/third-party/boost/libs/describe/include${RNOH_CPP_DIR}/third-party/boost/libs/mp11/include${RNOH_CPP_DIR}/third-party/boost/libs/iterator/include${RNOH_CPP_DIR}/third-party/boost/libs/detail/include${RNOH_CPP_DIR}/patches/react_native_core/react/renderer/textlayoutmanager/platform/harmony)configure_file(${RNOH_CPP_DIR}/third-party/folly/CMake/folly-config.h.cmake${RNOH_CPP_DIR}/third-party/folly/folly/folly-config.h ) file(GLOB GENERATED_CPP_FILES "./generated/*.cpp") # 添加rnoh動態共享包 add_library(rnoh SHARED"${RNOH_CPP_DIR}/RNOHOther.cpp""${RNOH_CPP_DIR}/third-party/folly/folly/lang/SafeAssert.cpp") # 鏈接其他so target_link_directories(rnoh PUBLIC ${OH_MODULE_DIR}/@rnoh/react-native-openharmony/libs/arm64-v8a) target_link_libraries(rnoh PUBLICrnoh_semilibace_napi.z.solibace_ndk.z.solibrawfile.z.solibhilog_ndk.z.solibnative_vsync.solibnative_drawing.solibc++_shared.solibhitrace_ndk.z.soreact_render_schedulerrrc_imagerrc_textrrc_textinputrrc_scrollviewreact_nativemodule_corereact_render_animationsjsinspectorhermesjsiloggerreact_configreact_debugreact_render_attributedstringreact_render_componentregistryreact_render_corereact_render_debugreact_render_graphicsreact_render_imagemanagerreact_render_mapbufferreact_render_mountingreact_render_templateprocessorreact_render_textlayoutmanagerreact_render_telemetryreact_render_uimanagerreact_utilsrrc_rootrrc_viewreact_render_leakcheckerreact_render_runtimeschedulerruntimeexecutor)if("$ENV{RNOH_C_API_ARCH}" STREQUAL "1")message("Experimental C-API architecture enabled")target_link_libraries(rnoh PUBLIC libqos.so)target_compile_definitions(rnoh PUBLIC C_API_ARCH) endif() # RNOH_END: add_package_subdirectories# 添加rnoh_app共享包 add_library(rnoh_app SHARED${GENERATED_CPP_FILES}"./PackageProvider.cpp""${RNOH_CPP_DIR}/RNOHOther.cpp""${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp" )target_link_libraries(rnoh_app PUBLIC rnoh)target_compile_options(rnoh_app PUBLIC ${folly_compile_options} -DRAW_PROPS_ENABLED -std=c++17)
-
將?
MyApplication/entry
?的?oh_modules
?文件夾刪除,點擊?entry
?文件夾,再點擊頂部菜單欄的?build
>Clean Project
?清除項目緩存。 -
點擊頂部菜單欄的?
File
?>?Sync and Refresh Project
?來執行?ohpm install
,執行完成后會在?entry
?目錄下生成?oh_modules
?文件夾。 -
點擊頂部菜單欄的?
Run
>Run 'entry'
?運行工程 。
運行結果:
-
-
打包 release的時候 ,har中沒有 x86_64 。所以最終會運行失敗。 有真機的小伙伴可以測試下。