Publishing GitBook to Github Pages

Markdown is nice. And it'd be really nice to get documentation or some notes up there with just Markdown, right? GitBook lets us do just that.

From their website:

GitBook is a modern publishing toolchain. Making both writing and collaboration easy.

Here's an example of a GitBook: Learn JavaScript.

GitBooks are however hosted on their own servers by default. If you're like me and you'd like to keep everything in GitHub, here's the way to go!

Creating your first GitBook

1. The GitBook CLI

npm install -g gitbook-cli

Not sure what npm is? It's a package manager for node. Installation instructions here.

2. Create a GIT repository

git init gitbook-test

3. Create a new GitBook

cd gitbook-test
gitbook init

Update the contents of the and files. Build and run the book using:

gitbook serve

Make sure you add a .gitignore like this one before making your first commit. If you'd like your pages to show up in the sidebar you'll need to update accordingly.

Set it up with GitHub

Create a new repo on GitHub and push your commits to it. If you're doing this for the first time, make sure you read everything that GitHub shows you so you understand what you're doing.

To publish a Github site, you need to push the source files to a gh-pages branch. Let's create that.

git branch gh-pages

Let's move to the newly created branch (gh-pages), push it to our Github repo, and come back to the original branch (master).

git checkout gh-pages
git push -u origin gh-pages
git checkout master

Set up a gulp task to publish to GitHub Pages

First, create a package.json file using yarn.init. After that, run the following command to install required dependencies:

yarn add gulp gulp-gh-pages gulp-load-plugins --dev

If you don't have yarn installed you may install it using npm install -g yarn.

If you don't have gulp installed globally run npm install -g gulp as well.

Create a new file called gulpfile.js and add the following code to it:

const gulp = require('gulp');
const gulpLoadPlugins = require('gulp-load-plugins');

const $ = gulpLoadPlugins();

// Publishes the site to GitHub Pages
gulp.task('publish', () => {
  console.log('Publishing to GH Pages');
  return gulp.src('./_book/**/*')
      origin: 'origin',
      branch: 'gh-pages'

We can now publish changes to the site using:

gulp publish

All we need to do is make sure we've run gitbook build or gitbook serve before that to make sure the _books folder has the lastest files.

Here's a test repo I built using the above steps.