Automatically Publishing a Vite Project to GitHub Pages

Here are my notes from publishing https://bgrins.github.io/editor-tests/ from https://github.com/bgrins/editor-tests. There's an action at https://github.com/peaceiris/actions-gh-pages that makes this easy without setting up additional API tokens, but there are a few Vite specific steps worth noting.

Create the project

If you don't already have one npm create vite@latest, and cd into the directory. Then:

git init
git add .
git commit -m "initial commit"
git branch -M main
git remote add origin http://github.com/username/repo-name.git
git push -u origin main

Create gh-pages branch

If you don't already have a gh-pages branch you can create an empty one like so:

git switch --orphan gh-pages
git commit --allow-empty -m "gh-pages"
git push origin gh-pages

Add files to the repo

Create a vite.config.js with:

import { defineConfig } from "vite";
export default defineConfig({
  base: "./",
});

Create a .github/workflows/node.js.yml with:

name: Node.js CI

on:
  push:
    branches: ["main"]
  pull_request:
    branches: ["main"]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Use Node.js 18.x
        uses: actions/setup-node@v3
        with:
          node-version: 18.x
          cache: "npm"
      - run: npm install
      - run: npm run build --if-present

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./dist

Update GitHub settings

At this point there's an action running at https://github.com/bgrins/editor-tests/actions which builds the project from scratch and publishes to the root of the gh-pages branch, making it available at something like https://bgrins.github.io/editor-tests/.