title: React Native环境搭建 date: 2023-03-31 description: 搭建React Native开发环境,采用VS Code 和 AndroidStudio进行开发的方式。
写在前面的话
本文仅记录除AndroidStudio以外的开发环境配置。
按照文档绝对能搭建并成功运行RN示例。若不行,就是网络问题。一定要使用稳定的代理软件。
安装依赖
必须安装的依赖或IDE有:Node、JDK 和 Android Studio,选装VS Code(推荐)。
必须安装 Android Studio 来获得编译 Android 应用所需的工具和环境。
Node
下载地址
NodeJS下载:https://nodejs.org/dist
以下摘自RN中文网
注意 Node 的版本应大于等于 14,安装完 Node 后建议设置 npm 镜像(淘宝源)以加速后面的过程(或使用科学上网工具)。
注意:不要使用 cnpm!cnpm 安装的模块路径比较奇怪,packager 不能正常识别!
# 使用nrm工具切换淘宝源
npx nrm use taobao
# 如果之后需要切换回官方源可使用
npx nrm use npm
JDK
JDK下载:https://adoptium.net/zh-CN/temurin/releases/?version=11
React Native 需要 JDK 11。你可以在命令行中输入 javac -version(请注意是 javac,不是 java)来查看你当前安装的 JDK 版本。如果版本不合要求,则可以去Temurin或Oracle JDK上下载(后者下载需注册登录)。
低于 0.67 版本的 React Native 需要 JDK 1.8 版本(官方也称 8 版本)。
Yarn
以下摘自RN中文网
Yarn是 Facebook 提供的替代 npm 的工具,可以加速 node 模块的下载。
npm install -g yarn
安装完 yarn 之后就可以用 yarn 代替 npm 了,例如用yarn代替npm install命令,用yarn add 某第三方库名代替npm install 某第三方库名。
Android SDK
以下摘自RN中文网
React Native 需要通过环境变量来了解你的 Android SDK 装在什么路径,从而正常进行编译。
因此需要将安卓SDK和安卓开发工具配置成环境变量
配置 ANDROID_HOME 环境变量
打开控制面板 -> 系统和安全 -> 系统 -> 高级系统设置 -> 高级 -> 环境变量 -> 新建,创建一个名为ANDROID_HOME的环境变量(系统或用户变量均可),指向你的 Android SDK 所在的目录,并将其添加至Path中。
可在 Android Studio 的"Preferences"菜单中查看 SDK 的真实路径,具体是Appearance & Behavior → System Settings → Android SDK。
把工具目录添加到环境变量 Path
打开控制面板 -> 系统和安全 -> 系统 -> 高级系统设置 -> 高级 -> 环境变量,选中Path变量,然后点击编辑。点击新建然后把这些工具目录路径添加进去:platform-tools、emulator、tools、tools/bin
%ANDROID_HOME%\platform-tools
%ANDROID_HOME%\emulator
%ANDROID_HOME%\tools
%ANDROID_HOME%\tools\bin
VS Code
下载并安装Visual Studio Code,下载地址:https://code.visualstudio.com/Download
安装React Native Tool,
启动VS Code,按“Ctrl+Shift+X”打开扩展,输入“React Native Tool”,下载安装React Native Tool相关插件。
插件安装可以参考使用vscode打造现代化的RN开发环境
VS Code 不能运行yarn命令的解决方式: 以管理员身份运行Power Shell(快捷键:win+x+a) 执行 set-ExecutionPolicy RemoteSigned 命令,并输入y选项
RN Cli
React Native命令行工具
如果你之前全局安装过旧的react-native-cli命令行工具,请使用npm uninstall -g react-native-cli卸载掉它以避免一些冲突:
npm uninstall -g react-native-cli
执行下列命令
npm install -g react-native-cli
React Native命令行工具安装成功后,可以通过react-native --help来查看支持的所有命令
react-native --help
创建项目
新建工程
如果你是想把 React Native 集成到现有的原生项目中,则步骤完全不同,请参考集成到现有原生应用。
此处,使用 React Native 内建的命令行工具来创建一个名为"AwesomeProject"的新项目。方式如下:
在空文件夹路径下,执行下列命令:
npx react-native init AwesomeProject
使用--version参数(注意是两个杠)创建指定版本的项目。注意版本号必须精确到两个小数点。
npx react-native init AwesomeProject --version X.XX.X
还可以使用--template来使用一些社区提供的模板,例如带有TypeScript配置的:
npx react-native init AwesomeProject --template react-native-template-typescript
注意:
若在创建项目时报错,内容如下:
D:\RN_Proj\node_modules\react-native-cli\index.js:302
cli.init(root, projectName);
^
TypeError: cli.init is not a function
at run (D:\RN_Proj\node_modules\react-native-cli\index.js:302:7)
at createProject (D:\RN_Proj\node_modules\react-native-cli\index.js:249:3)
at init (D:\RN_Proj\node_modules\react-native-cli\index.js:200:5)
at Object.
at Module._compile (node:internal/moduless/loader:1105:14)
at Object.Module._extensions..js (node:internal/moduless/loader:1159:10)
at Module.load (node:internal/moduless/loader:981:32)
at Function.Module._load (node:internal/moduless/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
解决方法参考:关于react-native init 创建项目报错 cli.init is not a function 问题解决
1. 在react-native init AwesomeProject 创建项目时,报错TypeError: cli.init is not a function.
2. 解决:产生这个问题的原因是:使用这种方式创建工程,react-native版本是0.69 版本上不适用。各位可以检查下自己安装的React-native的版本。改成:npx react-native init AwesomeProject --version 0.68.2 即可。
运行示例
确保运行了模拟器或者连接了真机,然后在项目目录中运行yarn android或者yarn react-native run-android:
yarn android
# 或者
yarn react-native run-android
此命令会对项目的原生部分进行编译,同时在另外一个命令行中启动Metro服务对 js 代码进行实时打包处理(类似 webpack)。Metro服务也可以使用yarn start命令单独启动。
注意:npx react-native run-android只是运行应用的方式之一,也可以使用AS启动项目原生安卓部分,使用VSCode 的终端启动 ‘Metro’。
如果配置没有问题,你应该可以看到应用自动安装到设备上并开始运行。注意第一次运行时需要下载大量编译依赖,耗时可能数十分钟。此过程严重依赖稳定的代理软件,否则将频繁遭遇链接超时和断开,导致无法运行。
注:建议在run-android成功后再尝试使用 Android Studio 启动。请不要轻易点击 Android Studio 中可能弹出的建议更新项目中某依赖项的建议,否则可能导致无法运行。
调试代码
Start
若文件夹中带有“node_modules”且其中依赖无需更改,则不用执行“npm install”。
AndroidStudio 打开项目文件夹中“android”文件夹; VisualStudio Code 打开项目文件夹根目录; 执行下面的命令,生成index.android.bundle(生成路径:/android/app/src/main/assets/),否则会出现红屏错误。
npx react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
或是,打开/android/app/build.gradle/,配置react的bundleInRelease、bundleInDebug,这会自动在AS build时生成bundle。
/**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle",
*
* // the entry file for bundle generation. If none specified and
* // "index.android.js" exists, it will be used. Otherwise "index.js" is
* // default. Can be overridden with ENTRY_FILE environment variable.
* entryFile: "index.android.js",
*
* // https://reactnative.dev/docs/performance#enable-the-ram-format
* bundleCommand: "ram-bundle",
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true,
* // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}'
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"],
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/
project.ext.react = [
enableHermes: false, // clean and rebuild if changing
//是否在发布模式下捆绑JS和资产
bundleInRelease: false,
//是否在调试模式下捆绑JS和资产
bundleInDebug: true,
]
Debug
AndroidStudio 开发调试方式未变,以下仅记录RN的调试过程。
VS Code配置调试模式
点击VS左侧菜单栏中“运行与调试”(Ctrl + Shift + D)展开运行和调试(绿色三角形旁)的下拉框选中"添加配置",选择对应配置(例如, React Native:Debug Android)
若只连接包生成工具,配置“Attach to packager”,即如下配置(launcher.json):
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Attach to packager",
"cwd": "${workspaceFolder}",
"type": "reactnative",
"request": "attach",
"isDynamic":true
},
]
}
JS 远程调试
Debug JS Remotely:该功能允许开发人员在 Chrome 中调试应用,其调试方式和调试 Web 应用一样。
打开浏览器调试页面 http://localhost:8081/debugger-ui (如果地址栏打开的是 ip 地址,则请自行改为 localhost),然后F12打开开发者工具,进行调试
React Native DevMenu
Reload 刷新页面,修改JS文件时,刷新功能才起作用,如新增文件或修改原生代码都需重新编译应用才会生效。Change Bundle Location 改变打包后的URL地址Show Element Inspector 是否显示元素检查器,查看到当前选中元素的位置、样式、层级关系、盒子模型信息等等,方便我们快速定位问题。Disable Fast Refresh 禁止快速刷新Show Perf Monitor 是否显示监控窗口,实时展示内存占用、UI 和 JS 的 FPS 等信息,帮助我们调试性能问题。Settings 性能调试设置Enable Sampling Profiler 是否开启采样分析器Debug 开启远程调试,可通过Chrome Developer Tools工具调试程序。选中后将打开网址为http://localhost:8081/debugger-ui/
点击“Change Bundle Location”,填写IP+端口
需确保手机与PC在一个网络下,或连上数据线采用ADB的reverse
所遇问题汇总
无法附加到包生成工具
执行"Attach to packager"时,出现错误弹窗,内容如下:
An error occurred while attaching debugger to the application. 无法附加到包生成工具。确定存在包生成工具并且其正在端口 8081 中运行吗? 如果包生成工具被配置为在另一个端口中运行,请确保将该端口添加到 settings.json。 (error code 504) (error code 1410)
解决方法:https://blog.csdn.net/DovSnier/article/details/100521167
针对手机的操作
使用如下命令:
adb reverse --remove-all
清理所有关联的端口,然后重新进行reverse 操作;
adb reverse tcp:8081 tcp:8081
这条命令的意思是,Android允许我们通过ADB,把Android上的某个端口映射到电脑(adb forward),或者把电脑的某个端口映射到Android系统(adb reverse),在这里假设电脑上开启的服务,监听的端口为8081。Android手机通过USB连接电脑后,在终端直接执行adb reverse tcp:8081 tcp:8081,然后在手机中访问127.0.0.1:8081,就可以访问到电脑上启动的服务了。
摇一摇手机,继续Debug JS Remotely 操作;
针对PC 的操作
重启包生成工具,然后再次选择并启动调试配置,此时显示Connecting to remote debugger ,等待片刻;如果持续性的出现Conneting to remote debugger 连接提示状态,那就后退页面一下,然后重新进入RN 页面,此时会连接成功;看到如下所示,表示调试已连接; OS: win32 x64 Adapter node: v10.11.0 x64 vscode-chrome-debug-core: 6.7.46 启动调试器应用辅助进程。 已建立代理(包生成工具)与 React Native 应用程序之间的连接 调试器辅助进程在端口 28960 上已加载运行时 此时,你应当能够看到,VSCode 底部的蓝条有蓝色变为黄色
另一个调试器已连接到包生成工具
执行"Attach to packager"时,出现错误弹窗,内容如下:
An error occurred while attaching debugger to the application. 另一个调试器已连接到包生成工具。请先将其关闭,然后再尝试使用VSCode进行调试。 (error code 505) (error code 1410)
根据错误提示即可解决,若还不行,重启VSCode。
参考链接
ReactNative中文网-搭建开发环境
ReactNative中文网-在设备上运行
VS code运行react项目与AS安卓项目
超详细 React Native 完全使用指南
react-native调试之 vscode调试
推荐链接
发表评论