This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

如何使用集成方法将 Expo 添加到原生应用

使用集成方法向现有原生(棕地)应用添加 Expo 和 React Native 的指南。


React Native 和 Expo 非常灵活,可以逐步采用,一次一个屏幕(甚至一个视图)。你可能会发现以这种方式使用 Expo 对你的特定应用来说是最合适的,或者你可能最终会在应用的更多部分慢慢采用它。无论哪种方式,这种灵活性都使开发者能够立即在原生应用中采用现代的跨平台工具,而无需冒完全重写的风险。

🌐 React Native and Expo are flexible and can be adopted incrementally, one screen (or even one view) at a time. You might even find that using Expo in this way is the best fit for your particular application, or you may end up slowly adopting it across more surfaces in your app. Either way, this flexibility allows enables developers to adopt modern, cross-platform tools in their native apps immediately instead of risking a complete rewrite.

本指南将指导你如何将 React Native 视图添加到现有的原生应用中。这里介绍的方法被称为“集成”方法,因为 React Native 和 Expo 是以与任何其他库相同的方式集成的。

🌐 This guide will walk you through the steps to add a React Native view into an existing native app. The approach covered here is what we call the "integrated" approach, because React Native and Expo are integrated in the same way that you would any other library.

信息 另一种流行的技术是我们称之为“隔离”方法的方法,在这种方法中,你的 Expo 应用被打包为一个库,并由主要的现有应用作为黑盒处理。详情请参见 隔离方法指南

先决条件

3 要求

1.

Node.js(长期支持版)

安装 Node.js 以运行 JavaScript 代码和 Expo CLI。

2.

Yarn

安装 Yarn 作为 JavaScript 依赖的包管理器。

3.

CocoaPods
iOS

安装 CocoaPods,这是 iOS 的依赖管理系统之一。 CocoaPods 是一个 Ruby gem,你可以使用 macOS 最新版本自带的 Ruby 来安装它。

设置环境指南了解更多信息。

🌐 Learn more from the Set up environment guide.

创建 Expo 项目

🌐 Create an Expo project

首先,在现有原生项目的根目录中创建一个 Expo 项目。

🌐 First, create an Expo project inside your existing native project's root directory.

Terminal
npx create-expo-app@latest my-project --template default@sdk-57

此命令会创建一个名为 my-project 的新目录,其中包含你的新 Expo 项目。虽然你可以给项目起任何名字,但本指南为了保持一致性使用 my-project。新项目包含一个示例 TypeScript 应用,以帮助你快速入门。

🌐 This command creates a new directory named my-project that contains your new Expo project. While you can name the project anything, this guide uses my-project for consistency. The new project includes an example TypeScript application to help you get started.

设置你的项目结构

🌐 Set up your project structure

一个标准的 React Native 项目会将原生代码放在 androidios 目录中。具体操作方式取决于你的项目,但可能非常简单,例如只需创建这些目录并将你的项目移到其中。例如:

🌐 A standard React Native project places native code in android and ios directories. The specifics of how to do this depend on your project, but it could be as simple as creating the directories and moving your projects there. For example:

Terminal
mkdir my-project/android
mv /path/to/your/android-project my-project/android/
无法将本地项目移动到 Android 和 iOS 目录吗?

建立一个单体仓库

🌐 Set up a monorepo

Monorepos,或称“单体仓库”,是包含多个应用或包的单一仓库。了解更多

🌐 Monorepos, or "monolithic repositories", are single repositories containing multiple apps or packages. Learn more.

设置单一代码库(monorepo)将确保即使有自定义的文件夹结构,Android 和 iOS 脚本也能够调用 Node 库中的命令。要设置 Yarn 单一代码库,请在项目根目录下创建一个 package.json 文件,并添加以下内容:

🌐 Setting up a monorepo will ensure that Android and iOS scripts will be able to invoke commands from Node libraries even with a custom folder structure. To set up a Yarn monorepo, create a package.json file at the root of your project and add the following content:

package.json
{ "version": "1.0.0", "private": true, "workspaces": ["my-project"] }

然后运行 yarn install 来安装依赖。这将确保 node_modules 安装在项目根目录,并且本地脚本能够与 React Native 代码交互。请确保将 ["my-project"] 改为你在上一步创建的 Expo 项目名称。

🌐 Then run yarn install to install the dependencies. This will ensure node_modules are installed at the root of your project, and that native scripts can interact with React Native code. Make sure to change ["my-project"] to the name of the Expo project you created in the previous step.

信息 选择使用单一代码库(monorepo)需要你在 Gradle/CocoaPods 中配置自定义项目根目录。这将在接下来的章节中讲解。

配置你的原生项目

🌐 Configuring your native project

要在 Android 上集成 React Native,你需要通过修改以下文件来配置本地项目:

🌐 To integrate React Native on Android, you need to configure the native project by modifying the following files:

  • Gradle 文件settings.gradle、顶层 build.gradleapp/build.gradle 以及 gradle.properties 用于添加 React Native Gradle 插件(RNGP)和其他属性。
  • AndroidManifest.xml:用于添加必要的权限。(了解更多)
  • MainActivity:用于加载你的 React Native 应用。

配置 Gradle

🌐 Configuring Gradle

1

首先编辑你的 settings.gradle 文件,并添加以下内容(参考 最简模板):

settings.gradle
// Configures the React Native Gradle Settings plugin used for autolinking pluginManagement { def reactNativeGradlePlugin = new File( providers.exec { workingDir(rootDir) commandLine("node", "--print", "require.resolve('@react-native/gradle-plugin/package.json', { paths: [require.resolve('react-native/package.json')] })") }.standardOutput.asText.get().trim() ).getParentFile().absolutePath includeBuild(reactNativeGradlePlugin) def expoPluginsPath = new File( providers.exec { workingDir(rootDir) commandLine("node", "--print", "require.resolve('expo-modules-autolinking/package.json', { paths: [require.resolve('expo/package.json')] })") }.standardOutput.asText.get().trim(), "../android/expo-gradle-plugin" ).absolutePath includeBuild(expoPluginsPath) } plugins { id("com.facebook.react.settings") id("expo-autolinking-settings") } extensions.configure(com.facebook.react.ReactSettingsExtension) { ex -> ex.autolinkLibrariesFromCommand(expoAutolinking.rnConfigCommand) } expoAutolinking.useExpoModules() // rootProject.name = 'HelloWorld' expoAutolinking.useExpoVersionCatalog() includeBuild(expoAutolinking.reactNativeGradlePlugin) // Include your existing Gradle modules here. // include(":app")
使用自定义文件夹结构吗?

如果你使用自定义的文件夹结构,你需要在 settings.gradle 中显式设置你的项目根目录,以便自动链接生效。修改以下几行:

🌐 If you're using a custom folder structure, you need to explicitly set your project root in settings.gradle for autolinking to work. Modify the following lines:

2

Then open your top-level build.gradle and include this line (as suggested from the bare minimum template):

This makes sure the React Native Gradle and the Expo plugins are available and applied inside your project.

3

Add the following lines inside your app's build.gradle file (usually app/build.gradle — you can use the bare minimum template file as reference):

Using a custom folder structure?

If you're using a custom folder structure, you need to adjust the projectRoot value to point to root of your Expo project in app/build.gradle. Modify the following lines:

4

Finally, open your app's gradle.properties file and add the following lines (use the bare minimum template file as reference):

gradle.properties
reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 newArchEnabled=true hermesEnabled=true

Configuring your manifest

1

First, make sure you have the INTERNET permission in your AndroidManifest.xml:

2

Now in your debug AndroidManifest.xml, enable cleartext traffic:

This is necessary for your app to communicate with your local Metro bundler via HTTP. You can use the AndroidManifest.xml files from the bare minimum template as a reference: main and debug

Integrating with your code

Now, you need to add some native code to start the React Native runtime and tell it to render your React components.

Updating your Application class

Start by updating your Application class to initialize React Native. You can use MainApplication.kt from the bare minimum template as a reference:

Creating a ReactActivity

Create a new Activity that will extend ReactActivity and host the React Native code. This activity will be responsible for starting the React Native runtime and rendering the React component. You can use the MainActivity.kt from bare minimum template file as a reference:

MyReactActivity.kt
// package <your-package-here> import android.os.Build import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate import expo.modules.ReactActivityDelegateWrapper class MyReactActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "main" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate { return ReactActivityDelegateWrapper( this, BuildConfig.IS_NEW_ARCHITECTURE_ENABLED, object : DefaultReactActivityDelegate( this, mainComponentName, fabricEnabled ){}) } }

Add the new Activity to your AndroidManifest.xml file, make sure to set the theme of MyReactActivity to Theme.AppCompat.Light.NoActionBar (or to any non-ActionBar theme) to avoid your application rendering an ActionBar on top of the React Native screen:

Now your activity is ready to run some JavaScript code.

Test your integration

You have completed all the basic steps to integrate React Native with your application. Now run the following command in the React Native directory to start the Metro bundler

Terminal
npm run start

Metro 将你的 TypeScript 应用代码构建成一个打包包,通过它的 HTTP 服务器提供服务,并将打包包从你的开发环境中的 localhost 分享到模拟器或设备,从而实现热重载。现在你可以像平常一样构建和运行你的应用。一旦你在应用中进入由 React 驱动的 Activity,它应该会从开发服务器加载 JavaScript 代码。

🌐 Metro builds your TypeScript application code into a bundle, serves it through its HTTP server, and shares the bundle from localhost on your developer environment to a simulator or device, allowing for hot reloading. Now you can build and run your app as normal. Once you reach your React-powered Activity inside the app, it should load the JavaScript code from the development server.