在 Github Pages 上使用 Parcel 构建部署 React 应用程序

IT技术 reactjs deployment github-pages parceljs
2021-04-29 01:53:35

我正在尝试在 Github Pages 上部署一个带有 Parcel 的 React 应用程序。

我已部署它,但该应用程序实际上并未在屏幕上呈现。我不明白我做错了什么。

包.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

3个回答

正如@tromgy 在讨论中指出的那样,问题的根源在于生成的html页面/在对各种资产的 url 引用之前包含字符。

例如,如果您有一个domain.com/subfolder/index.html包含的 html 文件<script src="/script.js">,浏览器将查找位于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)。通过将 a.作为参数传递,您可以告诉parcel/从输出中省略所以你的构建脚本应该是这样的:

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

(奇怪的是,在您的问题中,您显示了一个dev使用此选项命令,但我在示例存储库中没有看到该代码)

另一件需要注意的事情是您使用的是不受支持的 v1 版本的 Parcel。我将您升级到 v2 并在此 PR 中修复了上述问题

步骤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步

"homepage": "https://[USERNAME].github.io/[YOUR REPO NAME]",

第 3 步

npm install gh-pages --save-dev

步骤4

在 package.json 文件中添加脚本

"predeploy": "npm run build",
"deploy": "gh-pages -d build",

运行下面给出的命令

npm run deploy

经过数小时的研究,我发现当您使用react-router-dom>v4并部署到子域(例如//pet-adoption-appk在您的情况下)时,您必须提供具有子域值basename属性<BrowserRouter>在你的情况下,你必须像这样通过它<BrowserRouter basename="/pet-adoption-app">