簡體   English   中英

在 Github 頁面上使用 Parcel 部署 React 應用程序

[英]Deploying React app with Parcel build on Github Pages

我正在嘗試在 Github 頁面上部署一個帶有 Parcel 的 React 應用程序。

我已經部署了它,但應用程序實際上並沒有在屏幕上呈現。 我不明白我做錯了什么。

Package.json

{
  "name": "pet-adoption-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "homepage": "https://github.com/junaidshaikh-js/pet-adoption-app",
  "scripts": {
    "format": "prettier --write \"src/**/*.{js,jsx}\"",
    "lint": "eslint \"src/**/*.{js,jsx}\" --quiet",
    "dev": "parcel src/index.html --public-url /pet-adoption-app/",
    "predeploy": "npm build",
    "deploy": "gh-pages -d dist"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/junaidshaikh-js/pet-adoption-app.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/junaidshaikh-js/pet-adoption-app/issues"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.13.4",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/plugin-transform-runtime": "^7.16.4",
    "@babel/preset-env": "^7.13.5",
    "@babel/preset-react": "^7.12.13",
    "eslint": "^8.3.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-react": "^7.22.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "gh-pages": "^3.2.3",
    "parcel": "^1.12.3",
    "prettier": "^2.4.1"
  },
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0"
  }
}

這是實時部署的鏈接: https://junaidshaikh-js.github.io/pet-adoption-app/

這是 Github 回購: https://github.com/junaidshaikh-js/pet-adoption-app

步驟1

  1. git remote add origin [YOUR REPO LINK] 2.git add -A 3.git commit -m "Initial commit" 4.git push -u origin main

第 2 步“主頁”:“https://[USERNAME].github.io/[YOUR REPO NAME]”,

步驟 3 npm 安裝 gh-pages --save-dev

步驟 4 在 package.json 文件中添加腳本

“predeploy”:“npm run build”,“deploy”:“gh-pages -d build”,

運行 npm 下面給出的命令運行 deploy

正如@tromgy 在討論中指出的那樣,問題的根源在於生成的html頁面在 url 引用各種資產之前包含/字符。

例如,如果您在domain.com/subfolder/index.html中有一個包含<script src="/script.js">的 html 文件,則瀏覽器將在domain.com/script.js中查找該腳本,而不是domain.com/subfolder/script.js

如果您改為刪除/ (例如<script src="script.js"> ),瀏覽器將查找相對於 html 文件所在位置的腳本(例如domain.com/subfolder/script.js ),即可能是你想要的。

Parcel 支持--public-url選項來完成此操作(請參閱cli docstarget docs )。 通過傳遞一個. 作為參數,您可以告訴 parcel 省略 output 中的/ 因此,您的構建腳本將類似於:

parcel build src/index.html --public-url .

(奇怪的是,在您的問題中,您顯示了一個使用此選項的dev命令,但我在示例 repo 中沒有看到該代碼)

另一件需要注意的是,您使用的是不受支持的 v1 版本的包裹。 我將您升級到 v2 並在此 PR中修復了上述問題。

經過數小時的研究,我發現當您使用react-router-dom > v4並部署到子域(例如 //pet- basename //pet-adoption-appk在您的情況下)時,您必須在<BrowserRouter>帶有子域值。 在您的情況下,您必須像這樣傳遞它<BrowserRouter basename="/pet-adoption-app">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM