By doing some tinkering I figured out, that I can just follow the documentation but do everything inside my existing react native project. I have to provide my own OnLoad.cpp
and CMakeLists.txt however. This can be done by following the c++
-Documentation of React Native Turbo Modules.
Here is some more detailed information on how I achieved this:
Add this to your apps build.gradle
file:
android {
...
externalNativeBuild {
cmake {
path "src/main/jni/CMakeLists.txt"
}
}
}
After that place the following two files under src/main/jni
:
CMakeLists.txt
:
# Copyright (c) Meta Platforms, Inc. and affiliates.
cmake_minimum_required(VERSION 3.13)
project(appmodules)
include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake)
OnLoad.cpp
:
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <DefaultComponentsRegistry.h>
#include <DefaultTurboModuleManagerDelegate.h>
#include <fbjni/fbjni.h>
#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>
#include <rncli.h>
#include <<YourModuleNameHere>Spec.h>
namespace facebook {
namespace react {
void registerComponents(
std::shared_ptr<ComponentDescriptorProviderRegistry const> registry) {
rncli_registerProviders(registry);
}
std::shared_ptr<TurboModule> cxxModuleProvider(
const std::string &name,
const std::shared_ptr<CallInvoker> &jsInvoker) {
return nullptr;
}
std::shared_ptr<TurboModule> javaModuleProvider(
const std::string &name,
const JavaTurboModule::InitParams ¶ms) {
auto module = <YourModuleNameHere>Spec_ModuleProvider(name, params);
if(module != nullptr) {
return module;
}
return rncli_ModuleProvider(name, params);
}
} // namespace react
} // namespace facebook
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) {
return facebook::jni::initialize(vm, [] {
facebook::react::DefaultTurboModuleManagerDelegate::cxxModuleProvider =
&facebook::react::cxxModuleProvider;
facebook::react::DefaultTurboModuleManagerDelegate::javaModuleProvider =
&facebook::react::javaModuleProvider;
facebook::react::DefaultComponentsRegistry::
registerComponentDescriptorsFromEntryPoint =
&facebook::react::registerComponents;
});
}
The important part within the OnLoad.cpp
is this part in the javaModuleProvider
-Function:
...
auto module = <YourModuleNameHere>Spec_ModuleProvider(name, params);
if(module != nullptr) {
return module;
}
...
That way your Module will be loaded. Keep in mind to update <YourModuleNameHere>
to fit your module name (both in the import and within javaModuleProvider
).