【问题标题】:how to configure a react app for production如何为生产配置 React 应用程序
【发布时间】:2020-02-08 03:53:45
【问题描述】:

我想将我的 react 应用部署到生产环境(使用 heroku)。部署应用时,React 开发工具指示我的应用正在开发模式下运行

我将应用程序推送到heroku:https://lesamisdhubert.herokuapp.com/

我尝试设置环境变量: heroku config:set NODE_ENV=production

但是,当我 console.log(process.env.NODE_ENV) 时,它返回开发

在投入生产之前我也尝试过npm run build,但没有成功

这是我在 package.json 文件中的脚本:

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

但是console.log('node env --->', process.env.NODE_ENV); 返回“发展”

有人知道如何将我的 react 应用程序设置为生产模式吗?这是 npm run build 的问题吗? 非常感谢,我真的不明白这是从哪里来的......

【问题讨论】:

  • 你在heroku上安装了create-react-app buildpack吗?
  • 我想我没有:我做了一个npm run build 我按照本文使用部分中的步骤操作:github.com/zhukmj/…

标签: reactjs heroku


【解决方案1】:

我在 package.json 中替换了:

"scripts": {
    "dev": "react-scripts start",
    "start": "serve -s build",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "heroku-postbuild": "npm run build"
  }

我还创建了一个新的 Heroku 应用,它似乎可以工作

【讨论】:

    【解决方案2】:

    在 heroku 中配置环境变量时,您必须附加 REACT_APP_VARIABLENAME,然后设置其值,否则您将无法访问 env 变量。

    看看:https://github.com/mars/create-react-app-buildpack#compile-time-configuration

    您可以在 heroku 客户端中执行此操作


    【讨论】:

    • 嗨!我已经用过heroku config:set NODE_ENV=production,是不是也一样?
    • 您好,不,不是,请阅读我在此处发布的文章,为了访问环境变量以与 Heroku 反应,您必须将它们设置为 REACT_APP_NAMEOFVARIABLE
    • 好的,谢谢!我不太确定,但我更改了 package.json 文件中的脚本,它似乎可以工作。无论如何感谢您的帮助:)
    • 没问题,尝试更具体地说明您所做的事情并将其发布在您的答案中,以便如果有人遇到同样的问题,他们可以查看您的解决方案。很高兴能提供帮助!
    猜你喜欢
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多