Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何和react-native-config一起使用 #5

Closed
superchenwb opened this issue Nov 20, 2019 · 8 comments
Closed

如何和react-native-config一起使用 #5

superchenwb opened this issue Nov 20, 2019 · 8 comments

Comments

@superchenwb
Copy link

我的项目中使用react-native-config,编译时需要指定一个配置文件。不知道该如何使用?

@fwh1990
Copy link
Owner

fwh1990 commented Nov 20, 2019

可以准备两个文件,比如 .env.prod.env.local,开发时copy.env.local为.env文件,打包时copy.env.prod为.env文件。

@fwh1990
Copy link
Owner

fwh1990 commented Nov 20, 2019

正常来讲都是在package.json中预先定好脚本。

{
  "scripts": {
    "start": "cp -f .env.local .env && react-native start",
    "deploy": "cp -f .env.prod .env && upload-pgy"
  }
}

@fwh1990
Copy link
Owner

fwh1990 commented Nov 20, 2019

在新版的react-native中,不再建议使用react-native-config,你可以直接在代码中使用node.js的语法process.env.NODE_ENV来处理配置:

if (process.env.NODE_ENV === 'development') {
  // Do something
} else {
  // Do something
}

旧版本的RN可以使用transform-inline-environment-variables达到同样的效果

@superchenwb
Copy link
Author

但是,我的项目可能需要打包不止两个环境,比如说有开发环境,多个测试环境,以及正式环境。还有就是有一些涉及原生的,比如说极光推送的app_key的配置之类的

@fwh1990
Copy link
Owner

fwh1990 commented Nov 20, 2019

之前是怎么处理的呢?

@superchenwb
Copy link
Author

我是创建多个命令来打包的,这是我以前的项目的package.json里的scripts
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"dev": "react-native run-android",
"build": "cd android && ./gradlew assembleRelease",
"build:install": "cd android && SET ENVFILE=.env.test && ./gradlew installRelease",
"build:test": "cd android && SET ENVFILE=.env.test && ./gradlew assembleRelease",
"build:test:bash": "cd android && ENVFILE=.env.test ./gradlew assembleRelease",
"build:production": "cd android && SET ENVFILE=.env.production && ./gradlew assembleRelease",
"build:production:bash": "cd android && ENVFILE=.env.production ./gradlew assembleRelease",
"clean": "cd android && ./gradlew clean",
"test": "jest",
"fix-modal": "node node_modules/react-native-modal-translucent/scripts/translucent-modal.js",
"postinstall": "npm run fix-modal"
},

@fwh1990
Copy link
Owner

fwh1990 commented Nov 20, 2019

根据shell的特性,您可以做适当的更改达到同样的效果

{
  "scripts": {
    "deploy:test": "export ENVFILE=.env.test && upload-pgy",
    "deploy:production": "export ENVFILE=.env.production && upload-pgy"
  }
}

在scripts中定义的脚本会使用新的进程处理,使用export只影响新的进程和其子进程而不影响当前终端(父进程),与ENVFILE=.env.test ./gradlew assembleRelease这种写法效果一致

@superchenwb
Copy link
Author

我以为export 只能放在cd android 之后。

@fwh1990 fwh1990 pinned this issue Apr 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants