Hexo + GitHub Pages 搭建个人博客

你正在浏览的这个博客本身就是 Hexo 实现的。Hexo是一个“快速、简洁且高效的博客框架”,支持GitHub Flavored Markdown,支持主题和插件。其生成的是静态网页,可以直接部署在GitHub Pages上。

安装

以下都是在 Mac 上的操作,其他系统上可能有些不同

brew

Mac 上的包管理工具,为了方便装其他工具,官网上就可以找到安装方法:

1
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

装完后可以执行下

1
2
brew update
brew upgrade

git

1
brew install git

或者装XCode

node.js

可以直接去官网下,这里更推荐用nvm

1
2
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash
nvm install stable

hexo

1
npm install hexo-cli -g

写作

东西都安装好了!现在创建一个工作目录hexo-blog,然后在目录内执行

1
hexo init

一个hexo项目就创建完成了!可以看到这样的目录结构

1
2
3
4
5
6
7
8
9
hexo-blog/
├── _config.yml # 项目的配置
├── node_modules # node依赖
├── package-lock.json # node依赖描述
├── package.json # node依赖描述
├── public # 输出的静态网站
├── scaffolds # 模版
├── source # 源码
└── themes # 主题

然后用

1
hexo new hello

就可以创建出一篇标题为 hello 的新文章,文件在./source/_post/hello.md

Front-matter

文件最上方---包含的就是Front-matter,用来设置文章的标题、日期、分类、标签等属性

1
2
3
4
5
---
title: hello
date: 2019-03-07 18:00:03
tags:
---

可以参考官方文档

文章内容

文章内容默认用Markdown语法,可以看GitHub Guides

想要在首页展示一个阅读全文按钮而不是全文展示,只需要在文章中间加入一行<!-- more -->,首页上就只会展示这个标记之前的内容了

调试

1
hexo s

然后用浏览器打开http://localhost:4000就可以看到展示效果了

加入 debug 参数可以看到更多调试输出

1
hexo s --debug

部署

  1. 在GitHub 上新建一个仓库,取名为<username>.github.io<username>要替换成你自己的 GitHub username

  2. 在 Hexo 工作目录下执行

    1
    npm install hexo-deployer-git --save
  3. 打开 Hexo 工作目录下的_config.yml,找到deploy节点,配置成这样

    1
    2
    3
    4
    deploy:
    type: git
    repo: git@github.com:<username>/<username>.github.io.git
    branch: master

    同样的,<username>要替换成你自己的 GitHub username

  4. 执行

    1
    2
    hexo clean
    hexo g --d
  5. 完成了!现在打开https://<username>.github.io就是部署好之后的博客了。

    如果想使用自己的域名

    1. source目录下创建一个名为CNAME的文件(文件名必须全大写),里面写上你的域名
    2. 重新执行部署
    3. 在你的域名服务商中增加记录值为<username>.github.ioCNAME解析

    就可以啦。

主题

  • NexT
    1
    git clone https://github.com/theme-next/hexo-theme-next themes/next
    然后打开_config.ymltheme节点设置成theme: next

插件

  • hexo-all-minifier

    1
    2
    brew install libtool automake autoconf nasm
    npm install hexo-all-minifier --save

    可以压缩生成的html、js、css和图片

    实际用下来发现有些BUG,不要开启js_concatorimage_minifier这两项功能

  • local-search

    1
    2
    npm install hexo-generator-search --save
    npm install hexo-generator-searchdb --save

    然后编辑_config.yml增加

    1
    2
    3
    4
    5
    search:
    path: search.xml
    field: post
    format: html
    limit: 10000

    以及修改themes/next/_config.ymllocal_search节点

    1
    2
    local_search:
    enable: true

    可以给网站增加一个搜索功能