根据控制台input来定位特定的环境

为了说明这个问题,我正在使用popup的create-react-app作为我的项目的布局。

我有5个环境,我的应用程序将被部署到。 每个环境都有相同的服务(主要是),例如:

 //environment 1 https://environment1.service1.foo.bar https://environment1.service2.foo.bar //environment 2 https://environment2.service1.foo.bar https://environment2.service2.foo.bar 

为了在过去的项目(Angular / Gulp)上实现这一点,我有一个吞吐任务,基本上会寻找一个variables被传入

 gulp build --environment environment1 

代码如下所示:

 gulp.task('environment', ['clean-environment'], function() { log('Copying environment'); var environmentFile = config.environmentSrcDir + 'env2.js'; if (args.environment !== 'env2' || args.environment === 'env3' || args.environment === 'env4' || args.environment === 'evn5') { environmentFile = config.environmentSrcDir + args.environment + '.js'; } return gulp .src(environmentFile) .pipe(rename(config.environmentService)) .pipe(gulp.dest(config.root)); }); 

基本上指向正确的文件,其中包含正确的端点以及与该环境相关的其他相关variables。

我的问题是,鉴于我使用create-react-app作为起点,所以webpack和节点脚本,我将如何完成这样的事情。 基本上我想能够说, yarn build env1 ,然后项目设置常量或常量的文件作为“积极”的常数可以这么说。

如果您使用“Create-react-app”,则可以通过不同的.env文件定义开发环境variables。

链接: https : //github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-development-environment-variables-in-env

.ENV:

 REACT_APP_GOOGLE_CLIENT_ID = XXX-YYY-ZZZ.apps.googleusercontent.com REACT_APP_API_PROTOCOL = http: REACT_APP_API_HOST = localhost:3000 NODE_PATH = src/scripts PORT = 9001 

.env.production:

 REACT_APP_GOOGLE_CLIENT_ID = ZZZ-YYY-XXX.apps.googleusercontent.com REACT_APP_API_PROTOCOL = https: REACT_APP_API_HOST = api.my-applicaton.com NODE_PATH = src/scripts 

根据当前命令(启动/testing/编译)读取不同的.envconfiguration。 dev.env开始和testing。 prod.envbuild立。 如果自定义configuration不存在 – 从.env文件读取envvariables。 大段引用

您将会知道哪个.env文件将用于您的启动项目命令。

你应该在你的package.json文件的scripts对象下面有这样的东西: "start-js": "react-scripts start", "start": "npm-run-all -p watch-css start-js", "build": "npm run build-css && react-scripts build",然后你可以使用指定的命令启动你的项目。 从文档中,左侧的文件比右侧的文件更具优先权:

npm start: .env.development.local, .env.development, .env.local, .env npm run build: .env.production.local, .env.production, .env.local, .env npm test: .env.test.local, .env.test, .env (note .env.local is missing)

例如,如果您从npm run build开始,您将能够访问.env.production文件中定义的variables。

在JavaScript代码中,您可以使用process.env.REACT_APP_API_HOST。

另请参阅medium.com上的此链接: https ://medium.com/@tuchk4/why-i-love-create-react-app-e63b1be689a3