Node.js 我遗漏了一些关于环境的东西,你能给我解释一下吗?

Node.js 我遗漏了一些关于环境的东西,你能给我解释一下吗?,node.js,reactjs,dotenv,Node.js,Reactjs,Dotenv,我有一个非常基本的需求:根据环境为我的API存储不同的端点。假设有这样一个简单的文件: API_URL=http://localhost:8080 { ... ... "start": "react-scripts start", "start:stage": "env-cmd .env.stage.local react-scripts start", "start:production": "env-cmd .env.production.local react-scripts st

我有一个非常基本的需求:根据环境为我的API存储不同的端点。假设有这样一个简单的文件:

API_URL=http://localhost:8080
{
...
...
 "start": "react-scripts start",
 "start:stage": "env-cmd .env.stage.local react-scripts start",
 "start:production": "env-cmd .env.production.local react-scripts start",
 "build": "react-scripts build",
 "build:stage": "env-cmd .env.stage.local react-scripts build",
 "build:development": "env-cmd .env.development.local react-scripts build",
...
...
}
对于我的prod环境,它应该是:

API_URL=http://myprodServer
我还想要一个集成测试和一个uat端点

查看my package.json,我看到:

"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
所以我的想法是:

  • 在“build”和“start”附近放置一个命令行参数,以便指定本地和生产环境文件
  • 有办法访问我的应用程序中的上述配置,比如config.API\u URL
  • 现在,我来自SpringBoot,在SpringBoot中,每个环境都有一个文件

    我认为dotenv可能是我的解决方案,但我在他们的网站上看到两件奇怪的事情:

  • 请不要提交.env文件-->那么,我的同事应该如何构建我的应用程序?我通常至少推送本地和测试环境,同时将uat和生产文件直接保存在服务器下
  • 您应该只有一个.env文件-->好吧,这一个会毁了我:如果我只有一个文件,我应该如何处理多个环境

  • 我错过了什么?你能帮我解决我的问题吗?我是npm的新手,所以我有点困惑…

    看起来您正在使用CRA开发React应用程序。如果是这样,您的环境变量应该是
    REACT\u APP\u API\u URL=http://localhost:8080
    。注意前缀。如果使用CRA,则必须使用前缀。更多关于这个。如果操作正确,该变量应该可以在javascript中使用
    process.env.REACT\u APP\u API\u URL

    在工作中,我们每个人都在本地拥有一份.env文件的副本,因为我们不签入它。对于每个环境,我们有不同的
    .env
    文件,例如-
    .env.production
    .env.development
    .env.stage
    。然后,我们在
    包.json
    中为每个环境创建一个运行和构建脚本。使用软件包,我们的脚本可能如下所示:

    API_URL=http://localhost:8080
    
    {
    ...
    ...
     "start": "react-scripts start",
     "start:stage": "env-cmd .env.stage.local react-scripts start",
     "start:production": "env-cmd .env.production.local react-scripts start",
     "build": "react-scripts build",
     "build:stage": "env-cmd .env.stage.local react-scripts build",
     "build:development": "env-cmd .env.development.local react-scripts build",
    ...
    ...
    }
    
    除此之外,我们还为每个环境提供了一个git分支,以便在
    stage
    分支上运行
    npm run build:stage
    并部署到stage环境。对于生产,我们也会这样做


    在查看了一个多环境设置之后,这就是我所确定的,它可以正常工作。但是,我愿意改进流程。

    环境变量可以通过
    process.env
    process一样在NodeJ中访问。env.API\u URL
    dotenv
    是定义环境变量的替代品(方便)。您可以拥有一个
    config.js
    文件,在该文件中读取所有环境变量并导出配置文件,最后给出清晰的解释!谢谢,我遗漏了前缀:)但有一个问题:正如您指出的,我使用了CRA,package.json中是否需要dotenv依赖关系?或者我已经安装了CRA?是否在CRA的引擎盖下使用,我不确定。但你是对的,在这里你不需要依赖,因为CRA为你处理它。如果您没有使用CRA作为样板,那么您可以使用
    dotenv
    来完成工作。此外,如果您在旅行中遇到了更好的方法,或者可以想出更好的方法,请联系我们。我很想知道答案很好。我要补充的一点是,提供一个.env.example文件作为创建其他.env文件的模板有些常见。