loading...
Cover image for How to automatically deploy to GitLab pages w/ CI ๐Ÿš€

How to automatically deploy to GitLab pages w/ CI ๐Ÿš€

bryce profile image Bryce Dorn ใƒป2 min read

Long before GitHub actions were released, GitLab had pipelines. They can do a ton of things, one of the simplest is to build & deploy a static site. When I learned this, I moved my projects there and have been using it for that since.
GitLab logo
There are a ton of options when deploying a static site nowadays: Now/Surge/Glitch, the list goes on... They work but all have a major flaw: they all require an extra step to run. And I'm lazy. ๐Ÿ˜Œ๐Ÿ’ค


Automatic deploys (upon pushes to a branch) can be yours with just two steps: a build script and continuous integration (CI) configuration. Both take ~10 seconds to set up.

1. Build script ๐Ÿ”จ

As long as your project has a build script that produces artifacts, the output directory can be hosted automatically. I've been using Parcel, so if I just provide the CLI arg --out-dir public it will put the build output in public.

Since the GitLab page URL for this project has a subroute (the repository name), you'll need to specify a public URL so assets are linked to correctly. In Parcel land, this means adding --public-url /my-project/.

So for a project in Parcel, this is what the script should look like in package.json:

"build-gitlab": "parcel build src/index.html --out-dir public --public-url /my-project/"

Webpack can do all of this too, just in the config instead of args.

2. CI config โš™๏ธ

Make a .gitlab-ci.yml in the root of your project, and add this:

image: node:latest

pages:
  stage: deploy
  script:
  - npm install
  - npm run build-gitlab
  artifacts:
    paths:
    - public
  only:
  - master

This adds a job called deploy: it installs dependencies then runs our build script from above, and then hosts the artifacts. Obviously you can customize this config to your liking (changing deploy branch, etc), but adding this file and pushing to master will Just Workโ„ข๏ธ.


And that's it. Now every time you push to master it will trigger a deploy. Nice!

nice

Discussion

pic
Editor guide