GitHub 페이지에 ReactJS 앱(Vite를 사용하여 구축)을 배포하는 방법은 무엇입니까?

王林
풀어 주다: 2024-08-08 21:15:00
원래의
463명이 탐색했습니다.

[ 기술 ]: ReactJS – 기사 #2


빌드 도구의 차이로 인해 특히 배포 시 장애물이 발생합니다. 오늘은 그중 하나를 집중적으로 살펴보고 해결해 드리겠습니다.

요구사항을 수집하고, 설계하고, 개발하고, 테스트합니다. 엄청난! 이제 거의 배포 단계로 넘어갈 수 없습니다.

농담이에요. 백엔드와 데이터베이스를 사용하는 역동적이고 기능이 풍부하며 강력한(및 기타 50가지 형용사) 앱을 배포하는 것이 매우 까다롭다는 것을 알고 있습니다. 따라서 우선 우리는 간단한(너무 단순한) ReactJS 앱을 배포하는 방법을 배우겠습니다.

어디에 배포하나요? GitHub 페이지! 예, GitHub는 프로젝트의 소스 코드를 호스팅하거나 GitHub 페이지를 호스팅하여 순전히 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 프레임워크이지만 서버 측 렌더링, 정적 사이트 생성, 라우팅 등 웹 애플리케이션 구축을 위한 강력한 기능 세트를 제공합니다.

  • Gatsby: React를 기반으로 구축되어 성능과 SEO 이점을 제공하는 또 다른 인기 있는 정적 사이트 생성기입니다.

이제 NextJS 앱이 결국 ReactJS 앱이라는 것을 알게 되었습니다. 왜냐하면 NextJS는 ReactJS 라이브러리 위에 구축된 프레임워크이기 때문입니다.

그러나 어느 쪽이든, 프레임워크 앱(NextJS 앱)이 아닌 라이브러리 앱(ReactJS 앱)을 만들고 싶다면(제가 했던 일입니다) Vite 빌드 도구를 사용하여 그렇게 할 수 있습니다.

Vite를 사용하여 ReactJS 앱 만들기
터미널에서 다음 명령을 사용하여 JavaScript(기본값)를 사용하는 React 앱을 한 번에 만들 수 있습니다.

몰랐다면 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 저장소의 페이지 탭에는 다음 인터페이스가 표시됩니다.

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 페이지에 ReactJS 앱(Vite를 사용하여 구축)을 배포하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!