【问题标题】:How can we dynamically run different start scripts per local environment in React?我们如何在 React 中为每个本地环境动态运行不同的启动脚本?
【发布时间】:2020-08-29 00:01:08
【问题描述】:

作为我们开发环境的一部分,我们选择在端口 3006 上启动 React,而不是通常的 3000 端口。

在 Mac 上,您可以通过将以下内容添加到 package.json 来实现。

  "scripts": {
    "start": "PORT=3006 react-scripts start",

但在 Windows 上,您必须改为添加以下内容。

  "scripts": {
    "start": "set PORT=3006 && react-scripts start",

由于我们的开发人员同时使用两台机器(Mac 和 Windows),有没有一种好方法来处理每台机器上的不同启动脚本?

【问题讨论】:

    标签: reactjs environment-variables package.json


    【解决方案1】:

    您可以通过将其安装为开发依赖项来使用跨环境包

    npm install -S cross-env
    

    yarn add -D cross-env
    

    然后你可以简单地在 package.json 中编写你的命令,如下所示

    "scripts": {
        "start": " cross-env PORT=3006 react-scripts start",
    }
    

    现在这将适用于 Windows、Linux 甚至基于 Mac 的系统

    【讨论】:

      【解决方案2】:

      一种方法是这样的:

      "scripts" : {
          "start-windows" : "PORT=3006 react-scripts start",
          "start-mac" : "set PORT=3006 && react-scripts start"
      }
      

      【讨论】:

      • 有趣。然后我们只需调用yarn start-macyarn start-windows 在每个操作系统上启动项目
      【解决方案3】:

      请看this

      基本上只需在项目的根目录中添加.env 文件并添加

      PORT=3006
      

      当然这可以处理例如PORT 和链接中指定的其他配置,如果您需要其他配置,则需要使用 cross-env 之类的配置。

      【讨论】:

        猜你喜欢
        • 2022-01-15
        • 2016-02-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 1970-01-01
        • 2017-09-15
        相关资源
        最近更新 更多