You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过脚本切换App.js文件运行React Native项目?

实现通过脚本切换React Native入口App文件

当然可行,不用手动改注释,通过环境变量+自定义脚本就能搞定,步骤如下:

1. 修改index.js,用环境变量动态选择入口

把原来的index.js改成根据环境变量加载对应App文件:

import { AppRegistry } from 'react-native'

// 读取环境变量,默认用App.js
const targetApp = process.env.APP_TARGET || 'App'
const myApp = require(`./src/${targetApp}`).default

AppRegistry.registerComponent('Dummy app', () => myApp)

2. 在package.json里添加自定义脚本

为了兼容Windows、macOS、Linux,推荐先装个cross-env包统一环境变量设置方式:

npm install cross-env --save-dev

然后在package.json的scripts字段里添加这些命令:

"scripts": {
  "start": "react-native start",
  "start:app2": "cross-env APP_TARGET=App2 react-native start",
  "android": "react-native run-android",
  "android:app2": "cross-env APP_TARGET=App2 react-native run-android",
  "ios": "react-native run-ios",
  "ios:app2": "cross-env APP_TARGET=App2 react-native run-ios"
}

如果不想额外装包,也可以针对不同系统写脚本:

  • 对于macOS/Linux:
"start:app2": "APP_TARGET=App2 react-native start",
"android:app2": "APP_TARGET=App2 react-native run-android",
"ios:app2": "APP_TARGET=App2 react-native run-ios"
  • 对于Windows(CMD命令行):
"start:app2": "set APP_TARGET=App2 && react-native start",
"android:app2": "set APP_TARGET=App2 && react-native run-android",
"ios:app2": "set APP_TARGET=App2 && react-native run-ios"

3. 运行方式

要启动App2对应的项目,直接执行:

# 先启动metro
npm run start:app2
# 再打开对应平台(比如安卓)
npm run android:app2

内容的提问来源于stack exchange,提问作者Andy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:25:11