手摸手带你在github上自动部署应用

170 阅读2分钟

现成的可参考仓库:react-steps

1. 在 github 新建仓库(略
2. 添加 package.json 文件,提供对应打包命令,如:
{
  "scripts": {
    "build": "tsc && vite build"
  },
}

不一定是 build,可以自定义,在下面的步骤里对应 build 相应替换即可

3. 在项目根目录下,新建 .github/workflows/react-build.yml,内容如下:
name: Build and Deploy

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout Repository
      uses: actions/checkout@v2

    - name: Setup Node.js
      uses: actions/setup-node@v2
      with:
        node-version: '16'

    - name: Install Dependencies
      run: npm install

    - name: Build React App with Vite
      run: npm run build

    - name: Deploy to GitHub Pages
      uses: peaceiris/actions-gh-pages@v3
      with:
        github_token: ${{ secrets.GH_TOKEN }}
        publish_dir: ./docs

其中的 ./docs 代表 npm run build 执行后打包出来的文件夹,GH_TOKEN 需要在 github 上来生成和配置,后面会讲到。

4. github 上操作生成 GH_TOKEN

链接:github.com/settings/to…

image.png

image.png

image.png

5. 在项目中配置 GH_TOKEN

复制刚生成的 token

image.png

在项目目录下,设置这个token

image.png

image.png

image.png

6. 提交代码到 github
7. github 会根据 .github/workflows/react-build.yml 文件来进行构建,首次构建完后会自动创建一个 gh-pages 分支,该分支里的代码为 npm run build 生成的目录下的代码以及一个自动生成的 文件 .nojekell 文件

image.png

image.png

其中的第二步到第六步,对应的是 .github/workflows/react-build.yml 配置中的 jobs 下的 steps。

8. 配置 github-pages

image.png

9. 在项目中配置在线预览访问地址:

image.png

访问的地址格式为:https://用户名.github.io/项目名

10. 访问静态资源的根目录地址为 https://用户名.github.io 而真正的资源目录为 项目名/ 下,所以在打包时,html 里引入的地址,需要加入项目名,如下:

image.png

如果在一个 vite 打包的环境下,则可以在 vite.config.ts 中这样配置

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  base: '/react-starter', // 这里配置为 github 对应的项目名
  build: {
    outDir: "docs",
  },
  plugins: [react()],
})

以上,整个自动打包配置就完成了。