首页  >  文章  >  web前端  >  如何在 GitHub Pages 上部署 ReactJS 应用程序(使用 Vite 构建)?

如何在 GitHub Pages 上部署 ReactJS 应用程序(使用 Vite 构建)?

王林
王林原创
2024-08-08 21:15:00470浏览

[技术]:ReactJS – 文章 #2


构建工具的差异会导致障碍,尤其是在部署方面。今天我们将重点关注其中一个并为您解决它。

您收集需求、设计、开发和测试。伟大的!现在您几乎不需要进行部署。

开个玩笑。我知道,部署使用后端和数据库的动态、功能丰富、健壮(以及 50 个其他形容词)应用程序是相当棘手的。因此,作为初学者,我们将学习如何部署一个简单(太简单)的 ReactJS 应用程序。

我们将其部署在哪里? GitHub 页面!是的,GitHub 不仅限于托管项目的源代码或 GitHub Pages 来托管纯 HTML5 + CSS3 + JS 的静态网站。

您还可以在哪里部署前端应用程序?
平台列表如下:

  • Netlify(最适合初学者入门)
  • Vercel(最适合高级项目)
  • 激增

创建一个 ReactJS 应用程序!混乱螺旋。

如果你生活在 2024 年,我希望你不要使用 npx create-react-app ;创建 ReactJS 应用程序。

如果你查看 ReactJS 的官方文档,你会发现没有创建纯 ReactJS 应用程序的选项,但他们会坚持你使用 Next.js、Remix、Gatsby 等创建项目。

为什么突然放弃 npx create-react-app?
尽管对于许多 React 开发人员来说这是一个极好的起点,但由于它在以下方面的局限性,前端开发的格局已经发生了显着的变化:

  • 自以为是的结构
  • 定制困难
  • 性能开销

因此,开发人员求助于其他更好的替代方案,如下:

  • Vite:这个构建工具因其闪电般快速的开发服务器、高效的捆绑和灵活性而获得了巨大的受欢迎。

  • Next.js:虽然主要是一个 React 框架,但它提供了一组用于构建 Web 应用程序的强大功能,包括服务器端渲染、静态站点生成和路由。

  • Gatsby:另一个基于 React 构建的流行静态站点生成器,提供性能和 SEO 优势。

我现在知道 NextJS 应用程序最终是 ReactJS 应用程序,因为 NextJS 是一个构建在 ReactJS 库之上的框架。

但无论哪种方式,如果你不想创建一个框架应用程序(NextJS App)而是一个库应用程序(ReactJS App)(这是我所做的),你可以使用 Vite 构建工具来做到这一点。

使用 Vite 创建 ReactJS 应用
您可以在终端中使用以下命令一次性创建一个使用 JavaScript(默认)的 React App。

如果你不知道,React 官方支持 TypeScript。

npm create vite@latest deploy-reactjs-app-with-vite -- --template react

或者您可以使用以下命令逐步创建ReactJS应用程序:

npm create vite@latest

设置 GitHub!

让我们创建一个远程 GitHub 存储库。进入您的 GitHub 配置文件并创建一个远程 GitHub 存储库,您应该能够看到以下空存储库界面:

How to deploy ReactJS Apps (built using Vite) on GitHub Pages?

如果您进入“设置=>”在 GitHub 存储库的 Pages 选项卡中,您将看到以下界面:

How to deploy ReactJS Apps (built using Vite) on GitHub Pages?

它显示主分支或无。现在,您不必担心它,但请注意,我们将再次访问此页面。

一旦您开始该项目,我希望您在工作目录中执行以下命令(当然是按顺序执行):

  1. 在本地系统上初始化一个空的 git 存储库。
git init
  1. 通过暂存来跟踪所有文件。
git add .
  1. 创建一个检查点,拍摄上面阶段文件当前进度的快照:
 git commit -m "Added Project Files"
  1. 将本地存储库(在我们的系统上)与远程存储库(在 GitHub 上创建的存储库)连接。
 git remote add origin url_of_the_remote_git_repo_ending_with_.git
  1. 将检查点之前的进度从本地存储库上传到远程存储库。
 git push -u origin main

成功将更改推送到远程存储库后,您将在终端中看到以下输出:

How to deploy ReactJS Apps (built using Vite) on GitHub Pages?

现在,如果您刷新 GitHub 存储库,界面将如下所示:

How to deploy ReactJS Apps (built using Vite) on GitHub Pages?


Installing Dependencies and Crying over Errors:

Step 1: Installing gh-pages package

Right now we have just made 1 checkpoint and pushed it to our remote repo. We have NOT started to work on the deployment! YET!

Head to your working directory in your integrated terminal and fire up the following command:

npm install gh-pages --save-dev

This command will install and save gh-pages (github-pages) as a dev dependency or our project.

Dependencies are packages required for the application to run in production. Dev dependencies are packages needed only for development and testing.

Once completed, the terminal will look as follows (provides some positive acknowledgement):

How to deploy ReactJS Apps (built using Vite) on GitHub Pages?

Step 2: Update package.json

You have to add the following code to your package.json file.

{
    "homepage": "https://<username>.github.io/<repository>",
    "scripts": {
        "predeploy": "npm run build",
        "deploy": "gh-pages -d build",
        // ... other scripts
    }
    // other scripts
}

The above scripts are not specified during the project installation via Vite as they are gh-pages specific scripts.

The explanation for each is as follows:

  • homepage: The "homepage" field in the package.json file of a React project specifies the URL at which your app will be hosted. This field is particularly important when deploying a React application to GitHub Pages or any other static site hosting service that serves the site from a subdirectory.

Do update the values of and of the homepage property. In my case the values are ShrinivasV73 and Deploy-ReactJS-App-With-Vite respectively.

It is good to consider that the value are case-sensitive and should be placed accordingly.

  • "scripts" field in package.json allows you to define custom scripts that can be run using npm run .

    • "predeploy": "npm run build": This script runs automatically before the deploy script and it triggers the build process of your project.
    • "deploy": "gh-pages -d build": This script is used to deploy your built application to GitHub Pages. It uses the gh-pages package to publish the contents of the specified directory (build in this case) to the gh-pages branch of your GitHub repository.

Step 3: Deploy The App

Now that we've updated scripts as well, it is time to deploy the project. Head to the terminal and fire-up the following command to process:

npm run deploy

How to deploy ReactJS Apps (built using Vite) on GitHub Pages?

And boom ?, WE GET AN ERROR!

Error: ENOENT: no such file or directory, stat '<working-drectory>/build'

npm (node package manager) is trying to access the folder named build via the command npm run deploy which is actually npm run gh-pages -d build executed behind the scenes.

But it can't find any.

Bug Fix: #1 Updating the package.json file

Remember we didn't create a build directory by ourselves throughout this journey.

Vite outputs the build files to a dist directory by default and not the built directory, whereas tools like CRA (create-react-apps) use a build directory.

( This is exactly where the underlying functions and processes of different build tools manifests. )

We simply have to replace the build with dist in the deploy script inside the package.json file.

{ 
    "homepage": "https://<username>.github.io/<repository>", 
    "scripts": { 
        "predeploy": "npm run build", 
        "deploy": "gh-pages -d dist", 
        // ... other scripts } 
    // other scripts 
}

Bug Fix #2: Updating the vite.config.js

By default your vite.config.js file looks as follows:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
    plugins: [react()],
});

To make our app functions as expected without any bugs after successful deployment, we need to add base: '/Deploy-ReactJS-App-With-Vite/' to the object, which is passed to the defineConfig() method.

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
    plugins: [react()],
    base: '/Deploy-ReactJS-App-With-Vite/',
});

Setting the base property in vite.config.js is crucial for deploying a Vite-built app to a subdirectory, such as on GitHub Pages. It ensures that all asset paths are correctly prefixed with the subdirectory path, preventing broken links and missing resources.

Example:

  • Our repository is named Deploy-ReactJS-App-With-Vite and you are deploying it to GitHub Pages. The URL for your site will be https://username.github.io/Deploy-ReactJS-App-With-Vite/

  • If you don’t set the base property, the browser will try to load assets from https://username.github.io/ instead of https://username.github.io/Deploy-ReactJS-App-With-Vite/, resulting in missing resources.


Retry Deploying The App

Once you make the necessary changes to package.json file and vite.config.js file it's time to git add, commit, push. AGAIN!

Head to the working directory in the terminal and try deploying the app again:

npm run deploy

And this time when the app actually gets deployed to the Github pages, you'll see again, the positive acknowledgment to the terminal itself as follows:

How to deploy ReactJS Apps (built using Vite) on GitHub Pages?

If you refresh your GitHub repo go to the Settings => Pages tab of it, you'll see a new gh-pages branch added to the branches.

How to deploy ReactJS Apps (built using Vite) on GitHub Pages?

How do you access the app on web? Remember the value of homepage property in the package.json file? Yup! That's it.

In our case, it is https://ShrinivasV73.github.io/Deploy-ReactJS-App-With-Vite/


Conclusions

Congratulations! You've successfully learned how to deploy ReactJS App with Vite on GitHub Pages.

My recommendation for you folks would be to experiment as follows in different ways:

  • Create different font-end / full-stack apps like Angular or Vue.js and see how the configurations needs to be updated according to them.

  • Create different React Apps like Next.js or Remix or Gatsby

  • Use different platforms to deploy your front-end applications like vercel or netlify to see which option suits best for which use case.

In a nutshell, I started with experimentation and summarised my learning in this article. May be its your time to do so. Cheers!

If you think that my content is valuable or have any feedback,
do let me by reaching out to my following social media handles that you'll discover in my profile and the follows:

LinkedIn: https://www.linkedin.com/in/shrinivasv73/

Twitter (X): https://twitter.com/shrinivasv73

Instagram: https://www.instagram.com/shrinivasv73/

Email: shrinivasv73@gmail.com


以上是如何在 GitHub Pages 上部署 ReactJS 应用程序(使用 Vite 构建)?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn