DEV Community

loading...

A Step-by-Step Guide Deploying A Static Site or Single-page App to github pages

imm9o profile image Islam Muhammad ・2 min read

In this tutorial, you will learn how to set up and deploy your site to github pages manually and automatically using github actions.

Using gh-pages package

  1. Install gh-pages locally npm install gh-pages --save-dev
  2. Add new script to package.json file to deploy your website
    "scripts": {
      // replase dist with your build dir folder
      "deploy": "gh-pages -d [dist]"
    }
    /*
     * Replace <username> and <repositoryname> with your username
     * from GitHub and the name of your new repository.
     */
    "home": "https://<username>.github.io/<repositoryname>/",
Enter fullscreen mode Exit fullscreen mode
  1. Deploy your website to Github Pages by running this command npm run deploy

gh-pages behind the scenes will create another branch called gh-pages to push your build files into it

Using Github Actions

  1. Create folder .github

  2. Create [file].yml and name it with any name you like

  3. Open the file and past the content below


# Runs build and test
name: CI

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

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x]

    steps:
      - name: Checkout 🛎️
        uses: actions/checkout@v2.3.1 # If you're using actions/checkout@v2 you must set persist-credentials to false in most cases for the deployment to work correctly.
        with:
          persist-credentials: false
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}

      - name: Install and Build 🔧 # This example project is built using npm and outputs the result to the 'build' folder. Replace with the commands required to build your project, or remove this step entirely if your site is pre-built.
        run: |
          npm ci
          npm run build

      - name: Deploy 🚀
        uses: JamesIves/github-pages-deploy-action@3.7.1
        with:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          BRANCH: gh-pages # The branch the action should deploy to.
          FOLDER: _site # The folder the action should deploy.
          CLEAN: true # Automatically remove deleted files from the deploy branch
Enter fullscreen mode Exit fullscreen mode

Notes: The above set up will work on every push and every pull request created

Finally, you have to push to the main branch to watch your workflow working automatically

Discussion (0)

pic
Editor guide