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

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

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

[ 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]删除
最新教程 更多>
  • 如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    How to Resolve "General error: 2006 MySQL server has gone away" While Inserting RecordsIntroduction: connect to to to Database connect to t...
    编程 发布于2025-02-19
  • 如何限制动态大小的父元素中元素的滚动范围?
    如何限制动态大小的父元素中元素的滚动范围?
    在交互式界面中实现垂直滚动元素的CSS高度限制 考虑一个布局,其中我们具有与可滚动的映射div一起移动的subollable map div用户的垂直滚动,同时保持其与固定侧边栏的对齐方式。但是,地图的滚动无限期扩展,超过了视口的高度,阻止用户访问页面页脚。 可以限制地图的滚动,我们可以利用CSS...
    编程 发布于2025-02-19
  • 为什么使用Firefox后退按钮时JavaScript执行停止?
    为什么使用Firefox后退按钮时JavaScript执行停止?
    导航历史记录问题:JavaScript使用Firefox Back Back 此行为是由浏览器缓存JavaScript资源引起的。要解决此问题并确保在后续页面访问中执行脚本,Firefox用户应设置一个空功能以在window.onunload事件上调用。 pre> window.onload ...
    编程 发布于2025-02-19
  • 在保持其内容完整时,如何删除DIV元素?
    在保持其内容完整时,如何删除DIV元素?
    在保留其元素 display:cottents;在这种情况下是理想的选择。它导致元素的孩子出现为父母的直接子女,无视元素本身。当使用CSS网格或其他应该忽略包装元素的布局技术时,这是有价值的。 。容器{ 显示:Flex; } 。一 { 显示:内容; } 。一个P:第一子女{ 订单:2...
    编程 发布于2025-02-19
  • 如何在Java列表中有效计算元素的发生?
    如何在Java列表中有效计算元素的发生?
    计数列表中的元素出现在列表 中,在java编程中,列举列表中列举元素出现的任务来自列表。为此,收集框架提供了全面的工具套件。在这种情况下,Batocurrences变量将保持值3,代表动物列表中的“ BAT”出现的数量。 &&& [此方法是简单的,可以得出准确的结果,使其成为计算列表中元素出现的理...
    编程 发布于2025-02-19
  • 可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    https://webthemez.com/demo/sticky-multi-header-scroll/index.html </main> <section> display:grid; grid-template-col...
    编程 发布于2025-02-19
  • 如何使用替换指令在GO MOD中解析模块路径差异?
    如何使用替换指令在GO MOD中解析模块路径差异?
    克服go mod中的模块路径差异 coreos/bbolt:github.com/coreos/ [email受保护]:解析go.mod:模块将其路径声明为:go.etcd.io/bbolt [&bbolt `要解决此问题,您可以在go.mod文件中使用替换指令。只需在go.mod的末尾添加以...
    编程 发布于2025-02-19
  • 为什么PYTZ最初显示出意外的时区偏移?
    为什么PYTZ最初显示出意外的时区偏移?
    与pytz 最初从pytz获得特定的偏移。例如,亚洲/hong_kong最初显示一个七个小时37分钟的偏移: 差异源 考虑以下代码: < pre> import pytz 来自datetime import dateTime hk = pytz.timezone('asia/hon...
    编程 发布于2025-02-19
  • 如何使用Python的记录模块实现自定义处理?
    如何使用Python的记录模块实现自定义处理?
    使用Python的Loggging Module 确保正确处理和登录对于疑虑和维护的稳定性至关重要Python应用程序。尽管手动捕获和记录异常是一种可行的方法,但它可能乏味且容易出错。解决此问题,Python允许您覆盖默认的异常处理机制,并将其重定向为登录模块。这提供了一种方便而系统的方法来捕获和...
    编程 发布于2025-02-19
  • 如何使用PHP从XML文件中有效地检索属性值?
    如何使用PHP从XML文件中有效地检索属性值?
    从php 您的目标可能是检索“ varnum”属性值,其中提取数据的传统方法可能会使您感到困惑。 - > attributes()为$ attributeName => $ attributeValue){ echo $ attributeName,'=“',$ at...
    编程 发布于2025-02-19
  • Java是否允许多种返回类型:仔细研究通用方法?
    Java是否允许多种返回类型:仔细研究通用方法?
    在java中的多个返回类型:一个误解介绍,其中foo是自定义类。该方法声明似乎拥有两种返回类型:列表和E。但是,情况确实如此吗?通用方法:拆开神秘 [方法仅具有单一的返回类型。相反,它采用机制,如钻石符号“ ”。分解方法签名: :本节定义了一个通用类型参数,E。它表示该方法接受扩展FOO类的任何...
    编程 发布于2025-02-19
  • 如何克服PHP的功能重新定义限制?
    如何克服PHP的功能重新定义限制?
    克服PHP的函数重新定义限制在PHP中,多次定义一个相同名称的函数是一个no-no。尝试这样做,如提供的代码段所示,将导致可怕的“不能重新列出”错误。 //错误:“ cance redeclare foo()” 但是,PHP工具腰带中有一个隐藏的宝石:runkit扩展。它使您能够灵活地重新定义...
    编程 发布于2025-02-19
  • 如何在JavaScript对象中动态设置键?
    如何在JavaScript对象中动态设置键?
    如何为JavaScript对象变量创建动态键,尝试为JavaScript对象创建动态键,使用此Syntax jsObj['key' i] = 'example' 1;将不起作用。正确的方法采用方括号:他们维持一个长度属性,该属性反映了数字属性(索引)和一个数字属性的数量。标准对象没有模仿这...
    编程 发布于2025-02-19
  • 如何为PostgreSQL中的每个唯一标识符有效地检索最后一行?
    如何为PostgreSQL中的每个唯一标识符有效地检索最后一行?
    [2最后一行与数据集中的每个不同标识符关联。考虑以下数据: 1 2014-02-01 kjkj 1 2014-03-11 ajskj 3 2014-02-01 sfdg 3 2014-06-12 fdsa 为了检索数据集中每个唯一ID的最后一行信息,您可以在操作员上使用Postgres的有效效...
    编程 发布于2025-02-19

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

Copyright© 2022 湘ICP备2022001581号-3