It's quite straightforward to use GitLab Pages to deploy a Storybook instance per branch (and remove it whenever the branch will be removed). And yeah, it's irony to document this in a GitHub Gist 😅
You just need a .gitlab-ci.yml
like this one:
stages:
- setup
- build-and-test
- deployment
- pages
# stage: setup
setup:
stage: setup
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
artifacts:
paths:
- node_modules/
script:
- yarn
# stage: build-and-test (here I run linter, unit tests, and everything I want to build or test)
build:
stage: build-and-test
artifacts:
paths:
- dist/
script:
- yarn build
storybook:
stage: build-and-test
artifacts:
expire_in: 2 weeks
when: always
paths:
- storybook/
script:
- yarn build-storybook --output-dir storybook
# stage: deployment (here I deploy my app to specific stages or other artefacts like storybook)
deploy-storybook:
stage: deployment
script:
- echo "Enjoy the day. 🥳 Every job needs a script, but this job was just created to configure an environment."
environment:
name: storybook/$CI_COMMIT_REF_SLUG
url: https://your-orga.gitlab.io/your-group/your-project/$CI_COMMIT_REF_SLUG/storybook/
on_stop: remove STORYBOOK
only:
- branches
remove-storybook:
stage: deployment
cache:
key: 'my-storybook'
paths:
- public
script:
- rm -rf "public/$CI_COMMIT_REF_SLUG/storybook"
when: manual
variables:
GIT_STRATEGY: none # needed to prevent "Couldn't find remote ref" error
environment:
name: storybook/$CI_COMMIT_REF_SLUG
action: stop
# stage: pages (the stage name is custom, but the job NEEDS to be named pages)
pages:
stage: pages
cache:
key: 'my-storybook'
paths:
- public
script:
- if [ "$CI_COMMIT_REF_NAME" = "master" ]; then
mkdir -p public;
touch public/index.html;
echo "<!DOCTYPE HTML><script>window.location.href = 'https://your-orga.gitlab.io/your-group/your-project/master/storybook'</script>" > public/index.html;
fi;
- rm -rf "public/$CI_COMMIT_REF_SLUG"
- mkdir -p "public/$CI_COMMIT_REF_SLUG";
- mv storybook "public/$CI_COMMIT_REF_SLUG"
artifacts:
paths:
- public
Everything which needs to be deployed with GitLab Pages needs to be moved to the public/
directory. I place every Storybook build in a storybook/
directory in case I have more artefacts I want to deploy per branch with GitLab pages.
Because I use a dynamic environment which will cease to exist when the branch is closed the old Storybook build will be removed automatically.
(And I also create a super basic redirect for the root. 😅)
@donaldpipowitch How do you force storybook to load files from your-orga.gitlab.io/your-group/your-project/$CI_COMMIT_REF_SLUG/storybook/ instead of your-orga.gitlab.io? Right now I'm just getting 404/Mime-type errors