发布于 2026-01-06 3 阅读
0

正确地在 Heroku 上部署 React 应用

正确地在 Heroku 上部署 React 应用

在 Heroku 上部署 React 应用是部署过程中最简单的任务之一。但是,如果遗漏了一些重要步骤,可能会导致 react-router 的功能出现问题,或者将开发版本部署到生产环境。

那么,让我们来了解一下在 Heroku 上正确部署 React 应用的过程,以便获得生产优化的构建版本,并保持 react-router 的功能完整。

我使用 create-react-app 生成 React 应用的样板代码,并假设你也使用相同的工具。

  1. 第一步是使用 create-react-app 创建一个项目,并根据需要更新代码。
    $ create-react-app MyAwesomeApp
    $ cd MyAwesomeApp
  2. 接下来,我们需要在项目文件夹内初始化一个 git 仓库。
    $ git init
  3. 如果你还没有注册Heroku账号,请立即注册。

  4. 安装 Heroku CLI

    https://devcenter.heroku.com/articles/heroku-cli

  5. 使用您的邮箱和密码登录 Heroku CLI。


    $ heroku login

  6. 使用 create-react-app 构建包创建一个新的 Heroku 应用。此构建包会将 React UI 部署为静态网站。它还会使用 React 应用的生产版本进行部署。


    $ heroku create MY-AWESOME-APP --buildpack https://github.com/mars/create-react-app-buildpack.git

  7. 在项目根目录下新建一个名为 static.json 的文件,并将以下代码放入其中。


    {
    "root": "build/",
    "clean_urls": false,
    "routes": {
    "/**": "index.html"
    }
    }

  8. 现在提交所有更改并将代码推送到 Heroku master 分支。


    $ git add .

    $ git commit -m "initial commit"

    $ git push heroku master

  9. 您可以使用以下命令检查部署情况$ heroku open

请查看create-react-app-buildpackHeroku以了解更多详情。

原文链接:https://medium.com/@WebDevRaj/deploy-a-react-app-on-heroku-the-right-way-e17333d29169

文章来源:https://dev.to/webdevraj/deploy-a-react-app-on-heroku-the-right-way-5efo