Heim > Web-Frontend > js-Tutorial > Hauptteil

Wie stelle ich ReactJS-Apps (erstellt mit Vite) auf GitHub-Seiten bereit?

王林
Freigeben: 2024-08-08 21:15:00
Original
463 Leute haben es durchsucht

[Technologie]: ReactJS – Artikel #2


Unterschiede in den Build-Tools führen zu Hürden, insbesondere bei der Bereitstellung. Heute stellen wir eines davon vor und lösen es für Sie.

Sie erfassen Anforderungen, entwerfen, entwickeln und testen. Großartig! Jetzt kommen Sie kaum noch zur Bereitstellung.

Nur ​​ein Scherz. Ich weiß, dass die Bereitstellung dynamischer, funktionsreicher, robuster (und 50 anderer Adjektive) Apps, die Backend und Datenbanken verwenden, ziemlich schwierig ist. Daher werden wir zunächst lernen, wie man eine einfache (zu einfache) ReactJS-App bereitstellt.

Wo setzen wir es ein? GitHub-Seiten! Ja, GitHub ist nicht nur auf das Hosten des Quellcodes des Projekts oder GitHub-Seiten auf das Hosten statischer Websites beschränkt, die ausschließlich aus HTML5 + CSS3 + JS bestehen.

Wo sonst könnten Sie Ihre Front-End-Apps im Allgemeinen bereitstellen?
Die Liste der Plattformen lautet wie folgt:

  • Netlify (Am besten für Anfänger geeignet)
  • Vercel (am besten für fortgeschrittene Projekte geeignet)
  • Anstieg

Erstellen einer ReactJS-App! Die Verwirrungsspirale.

Wenn Sie im Jahr 2024 leben, hoffe ich, dass Sie npx create-react-app nicht verwenden. um eine ReactJS-App zu erstellen.

Wenn Sie sich die offiziellen Dokumente von ReactJS ansehen, werden Sie feststellen, dass es keine Option zum Erstellen einer reinen ReactJS-App gibt. Sie werden jedoch darauf bestanden, ein Projekt mit Next.js, Remix, Gatsby und mehr zu erstellen.

Warum die plötzliche Abkehr von der Npx-Create-React-App?
Obwohl es für viele React-Entwickler ein fantastischer Ausgangspunkt war, hat sich die Landschaft der Frontend-Entwicklung aufgrund ihrer Einschränkungen in Bezug auf Folgendes erheblich weiterentwickelt:

  • Meinungsorientierte Struktur
  • Schwierigkeiten bei der Anpassung
  • Leistungsaufwand

Daher griffen die Entwickler auf andere und bessere Alternativen zurück, die wie folgt lauten:

  • Vite: Dieses Build-Tool erfreut sich aufgrund seines blitzschnellen Entwicklungsservers, der effizienten Bündelung und Flexibilität großer Beliebtheit.

  • Next.js: Obwohl es in erster Linie ein React-Framework ist, bietet es einen robusten Satz an Funktionen zum Erstellen von Webanwendungen, einschließlich serverseitigem Rendering, statischer Site-Generierung und Routing.

  • Gatsby: Ein weiterer beliebter Generator für statische Websites, der auf React basiert und Leistungs- und SEO-Vorteile bietet.

Ich verstehe jetzt, dass NextJS-Apps letztendlich ReactJS-Apps sind, weil NextJS ein Framework ist, das auf der ReactJS-Bibliothek aufbaut.

Aber so oder so, wenn Sie keine Framework-App (NextJS App), sondern eine Bibliotheks-App (ReactJS App) erstellen möchten (was ich getan habe), können Sie dazu das Vite-Build-Tool verwenden.

Erstellen einer ReactJS-App mit Vite
Mit dem folgenden Befehl können Sie im Terminal eine React-App erstellen, die (standardmäßig) JavaScript auf einmal verwendet.

Wenn Sie es nicht wussten: React unterstützt offiziell TypeScript.

npm create vite@latest deploy-reactjs-app-with-vite -- --template react
Nach dem Login kopieren

Oder Sie können den folgenden Befehl verwenden, um einen ReactJS Apps Schritt-für-Schritt-Prozess zu erstellen:

npm create vite@latest
Nach dem Login kopieren

GitHub einrichten!

Lassen Sie uns ein Remote-GitHub-Repository erstellen. Gehen Sie zu Ihrem GitHub-Profil und erstellen Sie ein Remote-GitHub-Repository. Sie sollten die folgende Schnittstelle für ein leeres Repo sehen können:

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

Wenn Sie zu den Einstellungen => Auf der Registerkarte „Seiten“ Ihres GitHub-Repos sehen Sie die folgende Oberfläche:

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

Es wird entweder „Hauptzweig“ oder „Keine“ angezeigt. Im Moment müssen Sie sich darüber keine Sorgen machen, aber seien Sie sich bewusst, dass wir diese Seite noch einmal besuchen werden.

Sobald Sie an dem Projekt arbeiten, möchte ich, dass Sie die folgenden Befehle (natürlich nacheinander) in Ihrem Arbeitsverzeichnis ausführen:

  1. Initialisieren Sie ein leeres Git-Repo auf Ihrem lokalen System.
git init
Nach dem Login kopieren
  1. Verfolgen Sie alle Dateien, indem Sie sie bereitstellen.
git add .
Nach dem Login kopieren
  1. Erstellen Sie einen Prüfpunkt, der eine Momentaufnahme des aktuellen Fortschritts der oben aufgeführten Stufendatei(en) erstellt:
 git commit -m "Added Project Files"
Nach dem Login kopieren
  1. Verbinden Sie das lokale Repo (auf unserem System) mit dem Remote-Repo (dem auf GitHub erstellten).
 git remote add origin url_of_the_remote_git_repo_ending_with_.git
Nach dem Login kopieren
  1. Laden Sie den bis zu unserem Kontrollpunkt erzielten Fortschritt vom lokalen Repo zum Remote-Repo hoch.
 git push -u origin main

Nach dem Login kopieren

Sobald Sie die Änderungen erfolgreich in das Remote-Repository übertragen haben, erhalten Sie in Ihrem Terminal die folgende Ausgabe:

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

Wenn Sie nun das GitHub-Repository aktualisieren, würde die Benutzeroberfläche etwa wie folgt aussehen:

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
Nach dem Login kopieren

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
}
Nach dem Login kopieren

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
Nach dem Login kopieren
Nach dem Login kopieren

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'
Nach dem Login kopieren

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 
}
Nach dem Login kopieren

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()],
});
Nach dem Login kopieren

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/',
});
Nach dem Login kopieren

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
Nach dem Login kopieren
Nach dem Login kopieren

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


Das obige ist der detaillierte Inhalt vonWie stelle ich ReactJS-Apps (erstellt mit Vite) auf GitHub-Seiten bereit?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!