github actions自动部署

419 阅读2分钟

github主页

每个GitHub账号拥有一个主页站点和无数个项目站点

You get one site per GitHub account and organization, and unlimited project sites.

部署的时候需要注意公共路径的配置,否则会出现 404

If you are not using a custom domain name, then do not forget to specify that your project is not hosted at the server root.

// vue 项目,在部署的时候需要加入仓库前缀作为publicPath
module.exports = {
    publicPath: process.env.NODE_ENV === 'production'
        ? '/repository-name/'
        : '/'
}
// react项目在package.json中加入homepage字段,并更换用户名和仓库名称
"homepage":"https://yourusername.github.io/repository-name"

github flow

在项目根目录下创建 .github/workflows/ 路径,其中配置一个 yaml文件,文件名任意,在push操作之后,GitHub就会自动进行部署

github actions

GitHub持续部署就是一步一步执行actions的过程,你不用自己编写actions文件,GitHub官方维护了一个 actions市场

每个 action 就是一个独立脚本,因此可以做成代码仓库,使用userName/repoName的语法引用 action。比如,actions/setup-node就表示github.com/actions/setup-node这个仓库,它代表一个 action,作用是安装 Node.js。事实上,GitHub 官方的 actions 都放在 github.com/actions 里面。 既然 actions 是代码仓库,当然就有版本的概念,用户可以引用某个具体版本的 action。下面都是合法的 action 引用,用的就是 Git 的指针概念.

actions/setup-node@74bc508 # 指向一个 commit
actions/setup-node@v1.0    # 指向一个标签
actions/setup-node@master  # 指向一个分支

github flow 配置demo

name: buildAndDeploy.
on:
  # Triggers the workflow on push or pull request events but only for the main branch
  push:
    branches: [ main ]
  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "build"
  build:
    # The type of runner that the job will run on
    runs-on: ubuntu-latest
    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      - name: step one
        # Uses the default branch of a public repository
        # If you're using actions/checkout@v2 you must set persist-credentials to false in most cases for the deployment to work correctly.
        uses: actions/checkout@v2 
        with:
          persist-credentials: false
      - name: Install and Build
        run: |
          npm install
          npm run build
      - name: Deploy
        uses: JamesIves/github-pages-deploy-action@releases/v3
        with:
          ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }} # token生成见下方参考链接
          BRANCH: project-pages
          FOLDER: dist

参考链接