在 Github Pages 上部署 React

发布日期:2026-07-16 02:42:02   来源 : 杭州电子商务研究院    浏览量 :5
杭州电子商务研究院 发布日期:2026-07-16 02:42:02  
5

介绍

嗨!如果你正在阅读这篇文章,那么你可能正在尝试弄清楚如何将你的 React App 部署到 Github Pages,或者你想要一种快速的方法让你的 React 应用在公共网络上运行。别再说了!在本指南中,你将学习如何将你的 React App 部署到 Github Pages。

您需要遵循以下说明:

  • 节点 js

  • Npm(Node 预安装)或 Yarn

  • Github 账户

  • Git

准备应用程序

我已经用 Create-React-App 准备了一个演示应用程序,以便您可以快速跟进。如果您更喜欢部署使用 Create-React-App 构建的自定义应用程序,这些步骤也非常适合您。要克隆应用程序,请打开终端并运行:

      git clone https://github.com/Nyamador/ps-ghpages.git && cd ps-ghpages
    

现在安装应用程序的依赖项。

      yarn add # If you prefer yarn

OR

npm install # If you do not have yarn installed
    

运行应用程序

通过启动开发服务器来验证应用程序是否正在运行。

      yarn start OR npm start

# You should see the following output in your terminal

Compiled successfully!

You can now view styled in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://10.0.75.1:3000

Note that the development build is not optimized.
To create a production build, use yarn build.
    

访问https://localhost:3000在浏览器中查看该应用程序

创建你的存储库

为您的应用创建一个 Github 存储库。这是您构建的应用将部署到的地方。您可以在此处执行此操作。

构建应用程序

您在开发环境中运行的应用程序在服务器上运行,但在浏览器中运行的部署应用程序将无法启动 Web 服务器来提供您的静态资产。要生成使应用程序在浏览器中运行所需的静态资产(HTML、CSS 和 JavaScript),您必须运行构建来为您生成资产。幸运的是,Create-React-App 已经配置了这一点,因此您需要做的就是运行构建脚本,然后系统将为您生成可用于生产的软件包。让我们看看它是如何工作的。在应用程序的根目录(package.json 所在的位置)运行以下命令。

但在此之前,请将homepage添加到package.json。Create-React-App 将使用给定的 URL 来确定构建中的根 URL。

      "homepage" : "https://{yourusername}.github.io/{app-name}

#{yourusername} - Your githhub username
#{app-name} - Name of your app
    

现在运行以下命令来构建您的应用程序。

      yarn run build

		OR 

npm run build
    

请注意在您的项目根目录下为您生成的构建文件夹。

安装 Github Pages 包

现在您的应用已准备好发布,您需要为 Github Pages 配置它。为此,请在终端中运行以下命令安装 github pages 包。

      yarn add gh-pages

OR 

npm install --save gh-pages
    

添加部署脚本

package.json文件中,将部署脚本添加到脚本部分。目前它看起来应该像这样。

      "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
     #new
    "deploy": "gh-pages -b master -d build",
    "eject": "react-scripts eject"
  },
    

部署您的应用程序

现在使用您创建的部署脚本来部署您的应用程序。

      yarn run deploy

OR 

npm run deploy
    

您可以进一步调整构建脚本以自动构建和部署应用程序以供后续部署,如下所示:

      "scripts": {
    "start": "react-scripts start",
  
   "build": "react-scripts build",
     #new
     "predeploy": "yarn run build",
 
    "deploy": "gh-pages -b master -d build",  
    "test": "react-scripts test",
 
    "deploy": "gh-pages -b master -d build",
 
    "eject": "react-scripts eject"
 
  },
    

结论

呼!就是这样。现在你可以随时将任何 React 应用部署到 Github Pages。

您可以在此处阅读有关 Create-React-App 部署的更多信息

欢迎随时在 Twitter 上关注我@DesmondNyamador

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据