Maison > interface Web > js tutoriel > le corps du texte

Comment déployer des applications ReactJS (construites à l'aide de Vite) sur les pages GitHub ?

王林
Libérer: 2024-08-08 21:15:00
original
463 Les gens l'ont consulté

[ Technologie ] : ReactJS – Article #2


Les différences dans les outils de build entraînent des obstacles, en particulier lors du déploiement. Aujourd'hui, nous allons en mettre en lumière un et le résoudre pour vous.

Vous rassemblez les exigences, vous concevez, vous développez et vous testez. Super! Désormais, vous passerez à peine au déploiement.

Je plaisante. Je sais que déployer des applications dynamiques, riches en fonctionnalités et robustes (et 50 autres adjectifs) qui utilisent le backend et les bases de données est assez délicat. Par conséquent, pour commencer, nous allons apprendre à déployer une application ReactJS simple (trop simple).

Où le déployons-nous ? Pages GitHub ! Oui, GitHub ne vise pas seulement à héberger le code source du projet ou les pages GitHub pour héberger des sites Web statiques purement HTML5 + CSS3 + JS.

Où d'autre pourriez-vous déployer vos applications frontales en général ?
La liste des plateformes est la suivante :

  • Netlify (idéal pour les débutants)
  • Vercel (Meilleur pour les projets avancés)
  • Surtension

Créer une application ReactJS ! La spirale de la confusion.

Si vous vivez en 2024, j'espère que vous n'utilisez pas npx create-react-app pour créer l'application ReactJS.

Si vous regardez la documentation officielle de ReactJS, vous verrez qu'il n'y a pas d'option pour créer une application ReactJS pure, mais ils insisteront pour que vous créiez un projet en utilisant Next.js, Remix, Gatsby et plus encore.

Pourquoi cet abandon soudain de npx create-react-app ?
Bien qu'il s'agisse d'un point de départ fantastique pour de nombreux développeurs React, le paysage du développement frontend a considérablement évolué en raison de ses limites en ce qui concerne les éléments suivants :

  • Structure avisée
  • Difficulté de personnalisation
  • Frais généraux de performances

Ainsi, les développeurs ont eu recours à d'autres et meilleures alternatives qui étaient les suivantes :

  • Vite : cet outil de build a acquis une immense popularité grâce à son serveur de développement ultra-rapide, son regroupement efficace et sa flexibilité.

  • Next.js : bien qu'il s'agisse principalement d'un framework React, il offre un ensemble robuste de fonctionnalités pour la création d'applications Web, notamment le rendu côté serveur, la génération de sites statiques et le routage.

  • Gatsby : un autre générateur de sites statiques populaire construit sur React, offrant des avantages en termes de performances et de référencement.

Je comprends maintenant que les applications NextJS sont en fin de compte des applications ReactJS, car NextJS est un framework construit au-dessus de la bibliothèque ReactJS.

Mais de toute façon, si vous ne souhaitez pas créer une application-cadre (application NextJS) mais une application de bibliothèque (application ReactJS), (ce que j'ai fait), vous pouvez utiliser l'outil de construction Vite pour le faire.

Création d'une application ReactJS à l'aide de Vite
Vous pouvez utiliser la commande suivante dans le terminal pour créer une application React qui utilise JavaScript (par défaut) en une seule fois.

Si vous ne le saviez pas, React prend officiellement en charge TypeScript.

npm create vite@latest deploy-reactjs-app-with-vite -- --template react
Copier après la connexion

Ou vous pouvez utiliser la commande suivante pour créer une application ReactJS par un processus étape par étape :

npm create vite@latest
Copier après la connexion

Configuration de GitHub !

Créons un référentiel GitHub distant. Accédez à votre profil GitHub et créez un référentiel GitHub distant et vous devriez pouvoir voir l'interface suivante pour un dépôt vide :

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

Si vous allez dans Paramètres => Onglet Pages de votre dépôt GitHub, vous verrez l'interface suivante :

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

Il affiche soit la branche principale, soit Aucune. Pour le moment, vous n'avez pas à vous en préoccuper, mais sachez que nous allons revoir cette page à nouveau.

Une fois que vous travaillez sur le projet, je souhaite que vous exécutiez les commandes suivantes (séquentiellement, bien sûr) dans votre répertoire de travail :

  1. Initialisez un dépôt git vide sur votre système local.
git init
Copier après la connexion
  1. Suivez tous les fichiers en les mettant en scène.
git add .
Copier après la connexion
  1. Créez un point de contrôle qui prend un instantané de la progression actuelle du ou des fichiers d'étapes ci-dessus :
 git commit -m "Added Project Files"
Copier après la connexion
  1. Connectez le dépôt local (sur notre système) au dépôt distant (celui créé sur GitHub).
 git remote add origin url_of_the_remote_git_repo_ending_with_.git
Copier après la connexion
  1. Téléchargez les progrès réalisés jusqu'à notre point de contrôle du dépôt local vers le dépôt distant.
 git push -u origin main

Copier après la connexion

Une fois que vous avez réussi à transférer les modifications vers le référentiel distant, vous obtiendrez le résultat suivant dans votre terminal :

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

Maintenant, si vous actualisez le référentiel GitHub, l'interface ressemblerait à ceci :

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
Copier après la connexion

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
}
Copier après la connexion

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
Copier après la connexion
Copier après la connexion

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'
Copier après la connexion

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 
}
Copier après la connexion

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()],
});
Copier après la connexion

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/',
});
Copier après la connexion

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
Copier après la connexion
Copier après la connexion

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


Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!