”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 GitHub Pages 上部署 ReactJS 应用程序(使用 Vite 构建)?

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

发布于2024-08-16
浏览:285

[ Technology ]: ReactJS – Article #2


Differences in build tools lead to hurdles, especially in deployment. Today we'll spotlight one such and solve it for you.

You gather requirements, you design, you develop and you test. Great! Now you'll barely move to deployment.

Just kidding. I know, deploying dynamic, feature rich, robust ( and 50 other adjectives ) apps that use backend and databases is quite tricky. Hence, as a starter we're going to learn how to deploy a simple ( too simple ) ReactJS App.

Where are we deploying it? GitHub Pages! Yes, GitHub is not only scoped to hosting the project's source code or GitHub Pages to host static websites that are purely HTML5 CSS3 JS.

Where else could you deploy your front-end apps in general?
The list of platforms is as follows:

  • Netlify (Best for beginners to get started)
  • Vercel (Best for Advanced projects)
  • Surge

Creating a ReactJS App! The Confusion Spiral.

If you're living in 2024, I hope you don't use npx create-react-app to create ReactJS App.

If you look at the ReactJS's official docs, you'll see that there's no option to create a pure ReactJS App, but they'll insist you to create project using Next.js, Remix, Gatsby and more.

Why the sudden shift away from npx create-react-app?
Although, it was a fantastic starting point for many React developers, the landscape of frontend development has evolved significantly due it's limitations with respect to the following:

  • Opinionated Structure
  • Difficulty in Customization
  • Performance Overhead

Thus developers resorted to other and better alternatives which were as follows:

  • Vite: This build tool has gained immense popularity due to its lightning-fast development server, efficient bundling, and flexibility.

  • Next.js: While primarily a React framework, it offers a robust set of features for building web applications, including server-side rendering, static site generation, and routing.

  • Gatsby: Another popular static site generator built on React, offering performance and SEO benefits.

I now get it that NextJS Apps are in the end ReactJS Apps, because, NextJS is a framework built on-top-of ReactJS library.

But either way, if you didn't want to create a framework app (NextJS App) but a library app (ReactJS App), ( which is something I did ), you could using Vite build tool to do so.

Creating a ReactJS App using Vite
You can use the following command in the terminal to create a React App that uses JavaScript ( by default ) in one-go.

If you didn't know, React officially supports TypeScript.

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

Or you could use the following command to create a ReactJS Apps by step-by-step process:

npm create vite@latest

Setting the GitHub Up!

Let's create a Remote GitHub Repository. Got to your GitHub Profile and create a remote GitHub Repository and you should be able to see the following interface for an empty repo:

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

If you go to the Settings => Pages tab of your GitHub repo, you'll see the following interface:

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

It shows either main branch or None. Right now, you don't have to be concerned about it, but be aware that we're going to revisit this page again.

Once you work on the project, I want you to execute the following commands (sequentially, of course) in your working directory:

  1. Initialize an empty git repo on your local system.
git init
  1. Track All file by staging them.
git add .
  1. Create a Checkpoint that takes a snapshot of current progress of the stages file(s) in above:
 git commit -m "Added Project Files"
  1. Connect local repo (on our system) with the remote repo (the one created on GitHub).
 git remote add origin url_of_the_remote_git_repo_ending_with_.git
  1. Upload the progress made till our checkpoint from local repo to the remote repo.
 git push -u origin main

Once you successfully push the changes to the remote repository, you'll the following output in your terminal:

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

Now, if you refresh the GitHub Repository the interface would look something as follows:

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://.github.io/",
    "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 '/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://.github.io/", 
    "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: [email protected]


版本声明 本文转载于:https://dev.to/shrinivasv73/how-to-deploy-reactjs-apps-built-using-vite-on-github-pages-38bi?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何在 PHP 中使用数组函数向左旋转数组元素?
    如何在 PHP 中使用数组函数向左旋转数组元素?
    在 PHP 中向左旋转数组元素在 PHP 中旋转数组,将第一个元素移动到最后一个元素并重新索引数组,可以使用 PHP 的 array_push() 和 array_shift() 函数组合来实现。PHP 函数:PHP 没有专门用于旋转的内置函数数组。但是,以下代码片段演示了如何模拟所需的旋转行为:$...
    编程 发布于2024-11-06
  • 如何解决Java访问文件时出现“系统找不到指定的路径”错误?
    如何解决Java访问文件时出现“系统找不到指定的路径”错误?
    解决 Java 中遇到“系统找不到指定的路径”时的文件路径问题在 Java 项目中,尝试访问文本时遇到错误来自指定相对路径的文件。此错误是由于 java.io.File 类无法定位指定路径而产生的。要解决此问题,建议从类路径中检索文件,而不是依赖文件系统。通过这样做,您可以消除相对路径的需要,并确保...
    编程 发布于2024-11-06
  • Laravel 中的 defer() 函数如何工作?
    Laravel 中的 defer() 函数如何工作?
    Taylor Otwell 最近宣布了 Laravel 中的新函数 defer()。这只是对 defer() 函数如何工作以及使用它可能遇到的问题进行非常基本的概述。 找出问题 还记得您曾经需要从 API 获取某些内容,然后在幕后执行一些用户不关心但仍在等待的操作的路由吗?是的,我们都至少经历过一次...
    编程 发布于2024-11-06
  • 在 Python Notebook 中探索使用 PySpark、Pandas、DuckDB、Polars 和 DataFusion 的数据操作
    在 Python Notebook 中探索使用 PySpark、Pandas、DuckDB、Polars 和 DataFusion 的数据操作
    Apache Iceberg Crash Course: What is a Data Lakehouse and a Table Format? Free Copy of Apache Iceberg the Definitive Guide Free Apache Iceberg Crash ...
    编程 发布于2024-11-06
  • Vue + Tailwind 和动态类
    Vue + Tailwind 和动态类
    我最近在做的一个项目使用了Vite、Vue和Tailwind。 使用自定义颜色一段时间后,我遇到了一些困惑。 在模板中添加和使用自定义颜色不是问题 - 使用 Tailwind 文档使该过程非常清晰 // tailwind.config.js module.exports = { them...
    编程 发布于2024-11-06
  • 端到端(E 测试:综合指南
    端到端(E 测试:综合指南
    端到端测试简介 端到端(E2E)测试是软件开发生命周期的重要组成部分,确保整个应用程序流程从开始到结束都按预期运行。与专注于单个组件或几个模块之间交互的单元或集成测试不同,端到端测试从用户的角度验证整个系统。这种方法有助于识别应用程序不同部分交互时可能出现的任何问题,确保无缝且无错误的用户体验。 ...
    编程 发布于2024-11-06
  • 可以在 Go 结构标签中使用变量吗?
    可以在 Go 结构标签中使用变量吗?
    在 Go 结构体标签中嵌入变量Go 的结构体标签通常用于注释和元数据,通常涉及简单的字符串文字。但是,用户可能会遇到在这些标签中需要动态或计算值的情况。考虑以下结构,其中带有为 JSON 封送注释的“类型”字段:type Shape struct { Type string `json:&q...
    编程 发布于2024-11-06
  • 如何增强 Visual Studio 的构建详细程度以实现深入洞察?
    如何增强 Visual Studio 的构建详细程度以实现深入洞察?
    熟悉 Visual Studio 的构建详细程度需要全面了解 Visual Studio 构建过程背后的复杂细节?别再犹豫了!虽然使用 vcbuild 不会产生所需的详细输出,但 Visual Studio 的设置中隐藏着一个解决方案。采取以下简单步骤即可解锁大量信息:导航至 Visual Stud...
    编程 发布于2024-11-06
  • 开发者日记# 谁写的?
    开发者日记# 谁写的?
    有一个想法困扰着我。也许,我们无法识别它,但日复一日,我们周围越来越多的人工智能生成的内容。 LinkedIn 或其他平台上的有趣图片、视频或帖子。我对帖子的媒体内容没有疑问(很容易识别它何时生成、从库存中获取或创建),但我对帖子的内容表示怀疑。几乎每次我读一篇文章时,我都会想这是谁写的?是作者分享...
    编程 发布于2024-11-06
  • 哪种方法计算数据库行数更快:PDO::rowCount 或 COUNT(*)?为什么?
    哪种方法计算数据库行数更快:PDO::rowCount 或 COUNT(*)?为什么?
    PDO::rowCount 与 COUNT(*) 性能在数据库查询中计算行数时,选择使用 PDO:: rowCount 和 COUNT(*) 会显着影响性能。PDO::rowCountPDO::rowCount 返回受最后一个 SQL 语句影响的行数。但是,对于 SELECT 语句,某些数据库可能会...
    编程 发布于2024-11-06
  • PART# 使用 HTTP 进行大型数据集的高效文件传输系统
    PART# 使用 HTTP 进行大型数据集的高效文件传输系统
    让我们分解提供的HTML、PHP、JavaScript和CSS代码对于分块文件上传仪表板部分。 HTML 代码: 结构概述: Bootstrap for Layout:代码使用 Bootstrap 4.5.2 创建一个包含两个主要部分的响应式布局: 分块上传部分:用于...
    编程 发布于2024-11-06
  • 比较:Lithe 与其他 PHP 框架
    比较:Lithe 与其他 PHP 框架
    如果您正在为下一个项目探索 PHP 框架,很自然会遇到 Laravel、Symfony 和 Slim 等选项。但是,是什么让 Lithe 与这些更强大、更知名的框架区分开来呢?以下是一些突出 Lithe 如何脱颖而出的注意事项。 1. 轻量级和性能 Lithe 的设计重点关注轻量级架...
    编程 发布于2024-11-06
  • 编码风格指南:编写简洁代码的实用指南
    编码风格指南:编写简洁代码的实用指南
    在过去的五年里,我一直在不断尝试提高我的编码技能,其中之一就是学习和遵循最推荐的编码风格。 本指南旨在帮助您编写一致且优雅的代码,并包含一些提高代码可读性和可维护性的建议。它的灵感来自于社区中最受接受的流行指南,但进行了一些修改以更适合我的喜好。 值得一提的是,我是一名全栈 JavaScript 开...
    编程 发布于2024-11-06
  • 检查类型是否满足 Go 中的接口
    检查类型是否满足 Go 中的接口
    在Go中,开发人员经常使用接口来定义预期的行为,使代码灵活且健壮。但是如何确保类型真正实现接口,尤其是在大型代码库中? Go 提供了一种简单有效的方法来在编译时验证这一点,防止运行时错误的风险并使您的代码更加可靠和可读。 您可能见过类似的语法 var _ InterfaceName = TypeN...
    编程 发布于2024-11-06
  • 掌握 JavaScript 中的 &#this&# 关键字
    掌握 JavaScript 中的 &#this&# 关键字
    JavaScript 中的 this 关键字如果不理解的话可能会非常棘手。这是即使是经验丰富的开发人员也很难轻松掌握的事情之一,但一旦你掌握了,它可以为你节省大量时间。 在本文中,我们将了解它是什么、它在不同情况下如何工作以及使用它时不应陷入的常见错误。 在 JavaScript ...
    编程 发布于2024-11-06

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3