」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 GitHub Pages 上部署 ReactJS 應用程式(使用 Vite 建置)?

如何在 GitHub Pages 上部署 ReactJS 應用程式(使用 Vite 建置)?

發佈於2024-08-16
瀏覽:207

[ 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]刪除
最新教學 更多>
  • JavaScript 中字串連接的逐步指南
    JavaScript 中字串連接的逐步指南
    JavaScript 中的字串連接 是將兩個或多個字串連接起來形成單一字串的過程。本指南探討了實現此目的的不同方法,包括使用運算子、= 運算子、concat() 方法和範本文字。 每種方法都簡單有效,允許開發人員為各種用例(例如用戶訊息或 URL)建立動態字串。 模板文字尤其為字串連接提供了現...
    程式設計 發佈於2024-11-06
  • Web UX:向使用者顯示有意義的錯誤
    Web UX:向使用者顯示有意義的錯誤
    擁有一個用戶驅動且用戶友好的網站有時可能會很棘手,因為它會讓整個開發團隊將更多時間花在不會為功能和核心業務增加價值的事情上。然而,它可以在短期內幫助用戶並在長期內增加價值。對截止日期嚴格要求的專案經理可能會低估長期的附加價值。我不確定蘋果網站團隊是否屬實,但他們缺少一些出色的使用者體驗。 最近,我...
    程式設計 發佈於2024-11-06
  • 小型機械手
    小型機械手
    小型機械手臂新重大發布 代碼已完全重構並編碼為屬性操作的新支援 這是一個操作範例: $classFile = \Small\ClassManipulator\ClassManipulator::fromProject(__DIR__ . '/../..') ->getC...
    程式設計 發佈於2024-11-06
  • 機器學習專案中有效的模型版本管理
    機器學習專案中有效的模型版本管理
    在机器学习 (ML) 项目中,最关键的组件之一是版本管理。与传统软件开发不同,管理机器学习项目不仅涉及源代码,还涉及随着时间的推移而演变的数据和模型。这就需要一个强大的系统来确保所有这些组件的同步和可追溯性,以管理实验、选择最佳模型并最终将其部署到生产中。在这篇博文中,我们将探索有效管理 ML 模型...
    程式設計 發佈於2024-11-06
  • 如何在 PHP 中保留鍵的同時按列值對關聯數組進行分組?
    如何在 PHP 中保留鍵的同時按列值對關聯數組進行分組?
    在保留鍵的同時按列值對關聯數組進行分組考慮一個關聯數組的數組,每個數組代表一個具有“id”等屬性的實體和“名字”。面臨的挑戰是根據特定列“id”對這些數組進行分組,同時保留原始鍵。 為了實現這一點,我們可以使用 PHP 的 foreach 迴圈來迭代陣列。對於每個內部數組,我們提取“id”值並將其用...
    程式設計 發佈於2024-11-06
  • 如何在 Gradle 中排除特定的傳遞依賴?
    如何在 Gradle 中排除特定的傳遞依賴?
    用Gradle 排除傳遞依賴在Gradle 中,使用應用程式外掛程式產生jar 檔案時,可能會遇到傳遞依賴,您可能想要排除。為此,可以使用排除方法。 排除的預設行為最初,嘗試排除 org.slf4j:slf4j- 的所有實例log4j12 使用以下程式碼:configurations { run...
    程式設計 發佈於2024-11-06
  • 極簡生活的藝術
    極簡生活的藝術
    什麼是極簡生活? 極簡生活是一種有意減少擁有的財產數量和生活中雜亂的生活方式。這不僅是為了整理您的空間,也是為了簡化您的生活,專注於真正重要的事情,並減少干擾。 為什麼採用極簡主義? 頭腦清晰:擁有的東西越少,需要擔心的事情就越少,頭腦就越清晰。 財務自由:透過...
    程式設計 發佈於2024-11-06
  • Java 混淆之謎
    Java 混淆之謎
    Come play with our Java Obfuscator & try to deobfuscate this output. The price is the free activation code! Obfuscated Java code Your goal...
    程式設計 發佈於2024-11-06
  • 如何在沒有圖像的 Outlook 電子郵件中建立圓角?
    如何在沒有圖像的 Outlook 電子郵件中建立圓角?
    在沒有圖像的 Outlook 中設定圓角樣式使用 CSS 在電子郵件用戶端中建立圓角可以非常簡單。但是,使用 CSS border-radius 屬性的傳統方法在 Microsoft Outlook 中不起作用。在設計具有圓角元素的電子郵件時,此限制提出了挑戰。 不用擔心,有一個解決方案可以讓您在 ...
    程式設計 發佈於2024-11-06
  • 如何在Python中高效比較字典中相等的鍵值對?
    如何在Python中高效比較字典中相等的鍵值對?
    比較字典是否相等的鍵值對在Python中,比較字典以檢查鍵值對是否相等是一項常見任務。一種方法是迭代字典並使用 zip 和 iteritems 方法比較每一對字典。然而,還有一些替代方法可以提供更好的程式碼優雅性。 其中一種方法是使用字典理解來建立僅包含共享鍵值對的新字典。代碼如下:shared_i...
    程式設計 發佈於2024-11-06
  • 如何在 PHP 中使用數組函數向左旋轉數組元素?
    如何在 PHP 中使用數組函數向左旋轉數組元素?
    在PHP 中向左旋轉數組元素在PHP 中旋轉數組,將第一個元素移動到最後一個元素並重新索引數組,可以使用PHP 的array_push() 和array_shift() 函數組合來實現。 PHP 函數:PHP 沒有專門用於旋轉的內建函數數組。但是,以下程式碼片段示範如何模擬所需的旋轉行為:$numb...
    程式設計 發佈於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 = { theme:...
    程式設計 發佈於2024-11-06

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3