【问题标题】:Setting up React environment variables for dev and local为 dev 和 local 设置 React 环境变量
【发布时间】:2022-02-10 15:33:46
【问题描述】:

我刚开始为我的项目做出反应和设置环境变量。这就是我所做的..

  1. 添加 .env-cmdrc.json 如下

    {
     "development":{
     "REACT_APP_BASE_URL": "https://servername:port/"
     },
     "staging":{
     "REACT_APP_BASE_URL": "http://servername:port/"
     },
      "local":{
      "REACT_APP_BASE_URL": "http://localhost:port/"
      }
     }
    
  2. 已安装 npm

npm install env-cmd 或 npm install -g env-cmd

  1. 将 package.json 编辑如下:

     "start:development": "env-cmd -e development react-scripts start",
     "start:staging": "env-cmd -e staging react-scripts start",
     "start:local": "env-cmd -e local react-scripts start",
     "build:development": "env-cmd -e development react-scripts build",
     "build:staging": "env-cmd -e staging react-scripts build",
    
  2. 试过 - npm run start:development

    给了我 env-cmd 错误

  3. 又跑了

    npm install env-cmd

  4. 现在尝试了 - npm run start:development

在默认路径下找不到 .rc 文件:[./.env-cmdrc,./.env-cmdrc.js,./.env-cmdrc.json] at getRCFile

我是第一次这样做,希望有任何帮助..我在这里错过了什么..

【问题讨论】:

    标签: reactjs environment-variables node-modules env-cmd


    【解决方案1】:

    我试过你的代码,但效果很好。
    检查你的代码,确保你的配置文件.env-cmdrc.json的位置,它应该放在你项目的根目录下(与package.json同级)

    【讨论】:

      【解决方案2】:

      我建议使用 dotenv 包而不是 env-cmd

      1. 安装包 - npm i dotenv
      2. 在你的根目录中创建一个环境文件 - .env
      3. 声明一个变量 - REACT_APP_URL=http://localhost/....
      4. 使用变量 - process.env.REACT_APP_URL

      为了启动 React 应用程序,您需要检查您的 package.json 文件并确保它包含如下内容:

       "scripts": {
          "start": "react-scripts start",
          "build": "react-scripts build",
          "test": "react-scripts test",
          "eject": "react-scripts eject"
        },
      

      如果存在,您可以运行以下命令:npm start


      现在你可以开始编码了 :)

      【讨论】:

        猜你喜欢
        • 2020-11-30
        • 1970-01-01
        • 2022-01-01
        • 2016-01-12
        • 2019-04-15
        • 2020-07-24
        • 2018-09-17
        • 2015-09-03
        • 2013-01-29
        相关资源
        最近更新 更多