Create your blog on Github

Purpose

Explain how I create this blog with hexo and github.
I wanted to be able to write markdown posts and host them on github.

Prerequisite

  • Node.js
  • git
  • bash

Which blog framework

There is several blog framework. But for our case we need to generate a static blog to commit on our repository (github).
I search on google and find hexo : A fast, simple & powerful blog framework, it is based on Node.js.

Prepare your github repository

Github offers the possibility to have a web site with a domain like “username.github.io”. All information to activate it can be found here Github Page.
Configure github to access it with SSH. Have a look here.

Installing Hexo and configuration

I am not going to write the hexo doc but all information is on the official hexo website.

Once you have installed the package we can start our blog:

1
2
3
$ hexo init <folder>
$ cd <folder>
$ npm install

Once initialized, here’s what your project folder will look like:

1
2
3
4
5
6
7
8
.  
├── _config.yml
├── package.json
├── scaffolds
├── source
| ├── _drafts
| └── _posts
└── themes

If you create a new post and generate the blog.

1
2
hexo new <title>
hexo generate

A “public” folder will be create with the static web site. This is this folder we want to commit to our github repository.

Create or go to the “public” folder and init the repository.

Create a .gitignore file with the following content:

1
2
3
$ cat .gitignore                                                                                                                              
.*
*.sh

Now we are going to create a Bash script to automatically commit the repository. We want to do fresh commit without old branch. This effectively deletes old articles.
Create “publish.sh” in “public” folder.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/bash
# chmod +x publish.sh


date=$(date "+%d-%m-%Y %T")
commit_name="Update ${date}"

# create tmp branch
git checkout --orphan TEMP_BRANCH

git add -A

git commit -m "$commit_name"

# delete old branch
git branch -D main

# rename tmp branch to main
git branch -m main

# force update
git push -f origin main

Now go back to your hexo folder (cd ..) and create a new bash script “hexo_generate.sh”:

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
# chmod +x hexo_generate.sh

# clean public to sync source/_post , maybe unnecessary :D
rm -rf public/202* public/archives public/css public/fancybox public/index.html public/js public/tags public/atom.xml

# clean db
rm db.json

hexo generate --deploy --force

# run git add commit push
(cd public && ./publish.sh)

Don’t forget to chmod +x .sh script.

Now you can create articles and automatically publish the blog on github.

That’s it that’s all \o/