xiaoyh 的个人博客

一个只会敲代码的咸鱼

0%

用 hexo 在 Github Pages 上搭建个人博客

0. 开始前的准备

在开始正式步骤前 ,应先在 PC 机上安装并配置好以下两个软件:

  • git
  • node.js

1. 新建仓库

在自己的 github 上新建名为 <user-name>.github.io 的 public 仓库。

2. 搭建本地博客环境

2.1 安装 hexo

使用 npm 全局安装 hexo-cli

1
npm install hexo-cli -g

2.2 初始化项目

在你想创建博客项目的目录下打开终端,并键入以下命令,其中 <folder> 是项目文件夹名。

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

其中,最后一步的 npm install 是为了下载搭建博客项目所需要的一些工具(比如 hexo-server)。

3. 部署

项目中的 source\_posts 目录,就是写博客的地方。里面自带一个名为 hello-world.md 的初始博客文档,所有的博客都是项目根据里面的 markdown 文档生成的。
(如果想直接部署可以不管)在修改博客文档(详情见 4. 新建博客文档)后,应按照以下步骤将其部署至 Github 上:

首先,打开项目中的 _config.yml 文件,找到 deploy 字段,并按照以下的形式填写完整:

1
2
3
4
5
6
# Deployment
## Docs: https://hexo.io/docs/deployment.html
deploy:
type: git
repo: 你的仓库地址 # https://github.com/<user-name>/<user-name>.github.io
branch: master

然后,还需通过 npm 去下载一个工具 hexo-deployer-git ,把项目推到 github 上。

1
npm install hexo-deployer-git --save

安装后,依次键入以下命令即可部署到 github 。

1
2
hexo clean
hexo deploy

部署完成后,打开浏览器输入 https://<user-name>.github.io/ 即可看到效果。
当出现 404 时,只需再等一会儿,根据官方 Github Pages 的文档,需要花费 20 分钟以内的时间以更新你的网站。

Note: It can take up to 20 minutes for changes to your site to publish after you push the changes to GitHub.

至此,已经完成了个人博客的搭建及部署。

3.1 通过 hexo-server 本地查看效果

在部署到 github 前,如果想先看看博客的效果可通过 hexo-server 先部署到本地。如果没有,需先下载安装:

1
npm install hexo-server --save

安装完成后,输入以下命令以启动服务器,网站会在 http://localhost:4000 下启动。在服务器启动期间,Hexo 会监视文件变动并自动更新,无须重启服务器。

1
hexo server

如果想要修改端口,可:

1
hexo server -p 5000

3.2 部署优化

每次都要执行 hexo cleanhexo deploy,不如写个脚本。
在项目中的 package.json 里更新如下:

1
2
3
4
"scripts": {
// ...
"push": "hexo clean & hexo deploy"
}

部署命令为

1
npm run push

4. 新建博客文档

可以执行以下命令来创建一篇新文章:

1
hexo new [layout] <title>

其中 title 表示文件名和博客标题。