2025年2月11日火曜日

GitHub PagesにReactの静的なアプリをデプロイ

 いつも忘れるので、GitHub PagesにReactの静的なアプリをデプロイする方法を備忘録として残しておく。

package.jsonが次の内容の場合に、npm run rebuildを実行して、docs以下にビルドしたファイルをコピーして、それをGitHub Pagesで公開させている。

{
  "name": "developertool-react",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build && cp -r dist docs",
    "rebuild": "tsc && vite build && rm -R docs && cp -r dist docs",
    "git": "git add . && git commit -m 'update' && git push origin main",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "deploy": "npm run build && gh-pages -d dist"
  },
  "dependencies": {
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "styled-components": "^6.1.11"
  },
  "devDependencies": {
    "@types/node": "^20.14.10",
    "@types/react": "^18.3.3",
    "@types/react-dom": "^18.3.0",
    "@typescript-eslint/eslint-plugin": "^7.13.1",
    "@typescript-eslint/parser": "^7.13.1",
    "@vitejs/plugin-react-swc": "^3.5.0",
    "eslint": "^8.57.0",
    "eslint-plugin-react-hooks": "^4.6.2",
    "eslint-plugin-react-refresh": "^0.4.7",
    "typescript": "^5.2.2",
    "vite": "^5.3.1"
  }
}

実行するnpmとgitコマンドは次のとおり。

$ npm run rebuild

> developertool-react@0.0.0 rebuild
> tsc && vite build && rm -R docs && cp -r dist docs

vite v5.3.3 building for production...
 44 modules transformed.
dist/index.html                  0.39 kB  gzip:  0.28 kB
dist/assets/index-C3sMy72Z.js  169.27 kB  gzip: 55.94 kB
 built in 954ms

$ git add .
$ git commit -m "Add that text copies to clipboard."
[main 423acf6] Add that text copies to clipboard.
 3 files changed, 24 insertions(+), 13 deletions(-)
 rename docs/assets/{index-3gzwRWFv.js => index-C3sMy72Z.js} (75%)
$ git push -u origin main
Enumerating objects: 16, done.
Counting objects: 100% (16/16), done.
Delta compression using up to 4 threads
Compressing objects: 100% (7/7), done.
Writing objects: 100% (9/9), 55.43 KiB | 5.54 MiB/s, done.
Total 9 (delta 4), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (4/4), completed with 4 local objects.
To https://github.com/takaharu-kobayashi/developertool-react.git
   eef57a2..423acf6  main -> main
branch 'main' set up to track 'origin/main'.

実際に公開しているGitHun PagesのURLは次のとおり。

https://takaharu-kobayashi.github.io/developertool-react/