我们如何在 cra(createreactapp) 中在运行时传递环境或配置变量

Dap*_* Ms 2 environment-variables build-tools npm reactjs create-react-app

我们如何在 cra(createreactapp) 中在运行时传递环境或配置变量。我不想为不同的环境构建,而是在不同的环境中使用一个具有不同配置的构建

Sim*_*zen 5

我们将 create-react 应用程序构建为静态网站,并将它们直接推送到一个简单的 Web 服务器。这就是为什么你不能在那里使用 env 变量的原因。我们找到了一个很好的解决方法,我们计划写一篇关于它的简短文章:

1. 使用(一个)环境变量启动您的应用

假设您有一个开发、暂存和生产环境,就像我们做的大多数项目一样。

我们REACT_APP_ENV在启动脚本中只设置了一个 ENV 变量。每个环境都有自己的启动和构建脚本。

# package.json
# ...
"scripts": {
  "start": "REACT_APP_ENV=development react-scripts start",
  "start:staging": "REACT_APP_ENV=staging react-scripts start",
  "start:prod": "REACT_APP_ENV=production react-scripts start",
  "build:staging": "REACT_APP_ENV=staging react-scripts build",
  "build:prod": "REACT_APP_ENV=production react-scripts build"
},
Run Code Online (Sandbox Code Playgroud)

2.设置配置文件

在您的 create-react 应用程序中,您将配置文件存储在src/config/index.js. 在此配置文件中,您可以根据环境定义值。

# src/config/index.js
const env = process.env.REACT_APP_ENV

export const appConfig = {
  api: {
    networkInterface: ({
      development: 'http://localhost:5000/graphql',
      staging: 'https://project-staging.herokuapp.com/graphql',
      production: 'https://project.herokuapp.com/graphql',
    })[env],
    // add more here
  },
}

export default appConfig
Run Code Online (Sandbox Code Playgroud)

3. 用法

在应用程序中,您可以像这样简单地访问配置:

import config from './src/config'

# usage
config.api.networkInterface 
Run Code Online (Sandbox Code Playgroud)

  • 好方法。但你仍然根据环境构建它,对吧?我希望它构建一次并在具有不同配置文件的所有环境中使用相同的内容 (2认同)