Bagaimana untuk menggunakan Aplikasi ReactJS (dibina menggunakan Vite) pada Halaman GitHub?

王林
Lepaskan: 2024-08-08 21:15:00
asal
464 orang telah melayarinya

[ Teknologi ]: ReactJS – Artikel #2


Perbezaan dalam alat binaan membawa kepada halangan, terutamanya dalam penggunaan. Hari ini kami akan menonjolkan satu perkara sedemikian dan menyelesaikannya untuk anda.

Anda mengumpulkan keperluan, anda mereka bentuk, anda membangunkan dan anda menguji. Hebat! Kini anda hampir tidak akan beralih ke penempatan.

Gurau sahaja. Saya tahu, menggunakan apl dinamik, kaya ciri, mantap (dan 50 kata sifat lain) yang menggunakan bahagian belakang dan pangkalan data adalah agak rumit. Oleh itu, sebagai permulaan, kami akan belajar cara menggunakan Apl ReactJS yang mudah (terlalu ringkas).

Di manakah kita akan menempatkannya? Halaman GitHub! Ya, GitHub bukan sahaja merangkumi untuk mengehos kod sumber projek atau Halaman GitHub untuk mengehoskan tapak web statik yang semata-mata HTML5 + CSS3 + JS.

Di manakah lagi anda boleh menggunakan apl bahagian hadapan anda secara umum?
Senarai platform adalah seperti berikut:

  • Netlify (Terbaik untuk pemula untuk bermula)
  • Vercel (Terbaik untuk projek Lanjutan)
  • Lonjakan

Mencipta Apl ReactJS! Lingkaran Kekeliruan.

Jika anda hidup pada tahun 2024, saya harap anda tidak menggunakan npx create-react-app untuk mencipta Apl ReactJS.

Jika anda melihat pada dokumen rasmi ReactJS, anda akan melihat bahawa tiada pilihan untuk mencipta Apl ReactJS tulen, tetapi mereka akan mendesak anda untuk membuat projek menggunakan Next.js, Remix, Gatsby dan banyak lagi.

Mengapa beralih secara tiba-tiba daripada npx create-react-app?
Walaupun, ia merupakan titik permulaan yang hebat untuk kebanyakan pembangun React, landskap pembangunan bahagian hadapan telah berkembang dengan ketara disebabkan pengehadannya berkenaan dengan perkara berikut:

  • Struktur Berpendapat
  • Kesukaran dalam Penyesuaian
  • Overhed Prestasi

Oleh itu pembangun menggunakan alternatif lain dan lebih baik seperti berikut:

  • Vite: Alat binaan ini telah mendapat populariti yang besar kerana pelayan pembangunan sepantas kilat, penggabungan yang cekap dan fleksibiliti.

  • Next.js: Walaupun terutamanya rangka kerja React, ia menawarkan set ciri yang mantap untuk membina aplikasi web, termasuk pemaparan sebelah pelayan, penjanaan tapak statik dan penghalaan.

  • Gatsby: Satu lagi penjana tapak statik popular yang dibina pada React, menawarkan prestasi dan faedah SEO.

Sekarang saya faham bahawa Aplikasi NextJS pada akhirnya adalah Aplikasi ReactJS, kerana, NextJS ialah rangka kerja yang dibina di atas perpustakaan ReactJS.

Tetapi dalam apa jua cara, jika anda tidak mahu mencipta apl rangka kerja (NextJS App) tetapi apl perpustakaan (ReactJS App), (yang saya lakukan ), anda boleh menggunakan alat bina Vite untuk berbuat demikian.

Mencipta Apl ReactJS menggunakan Vite
Anda boleh menggunakan arahan berikut dalam terminal untuk mencipta Apl React yang menggunakan JavaScript (secara lalai) sekali gus.

Jika anda tidak tahu, React secara rasmi menyokong TypeScript.

npm create vite@latest deploy-reactjs-app-with-vite -- --template react
Salin selepas log masuk

Atau anda boleh menggunakan arahan berikut untuk mencipta Aplikasi ReactJS mengikut proses langkah demi langkah:

npm create vite@latest
Salin selepas log masuk

Menetapkan GitHub Up!

Mari kita buat Repositori GitHub Jauh. Pergi ke Profil GitHub anda dan buat Repositori GitHub jauh dan anda sepatutnya dapat melihat antara muka berikut untuk repo kosong:

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

Jika anda pergi ke Tetapan => Tab halaman repo GitHub anda, anda akan melihat antara muka berikut:

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

Ia menunjukkan sama ada cawangan utama atau Tiada. Buat masa ini, anda tidak perlu risau tentangnya, tetapi maklum bahawa kami akan melawat semula halaman ini sekali lagi.

Sebaik sahaja anda mengerjakan projek, saya mahu anda melaksanakan arahan berikut (secara berurutan, sudah tentu) dalam direktori kerja anda:

  1. Mulakan repo git kosong pada sistem setempat anda.
git init
Salin selepas log masuk
  1. Jejaki Semua fail dengan mementaskannya.
git add .
Salin selepas log masuk
  1. Buat Pusat Pemeriksaan yang mengambil gambar kemajuan semasa fail peringkat di atas:
 git commit -m "Added Project Files"
Salin selepas log masuk
  1. Sambungkan repo tempatan (pada sistem kami) dengan repo jauh (yang dibuat pada GitHub).
 git remote add origin url_of_the_remote_git_repo_ending_with_.git
Salin selepas log masuk
  1. Muat naik kemajuan yang dibuat sehingga pusat pemeriksaan kami dari repo tempatan ke repo jauh.
 git push -u origin main

Salin selepas log masuk

Sebaik sahaja anda berjaya menolak perubahan pada repositori jauh, anda akan mengeluarkan output berikut dalam terminal anda:

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

Sekarang, jika anda memuat semula Repositori GitHub, antara muka akan kelihatan seperti berikut:

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
Salin selepas log masuk

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
}
Salin selepas log masuk

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
Salin selepas log masuk
Salin selepas log masuk

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'
Salin selepas log masuk

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 
}
Salin selepas log masuk

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()],
});
Salin selepas log masuk

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/',
});
Salin selepas log masuk

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
Salin selepas log masuk
Salin selepas log masuk

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


Atas ialah kandungan terperinci Bagaimana untuk menggunakan Aplikasi ReactJS (dibina menggunakan Vite) pada Halaman GitHub?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!