使用Hexo在Github Pages上部署静态博客

Tanphoon / 2023-05-13 / 原文

使用Hexo在Github Pages上部署静态博客

写在前面

本文写于2023/3/23,具体配置步骤具有时效性,后续如有必要会持续更新。

阅读本教程需要有 Git 和 Github 基础,对 Markdown 语法有一定的了解。

什么是Github Pages?

GitHub Pages 是一项静态站点托管服务,它直接从 GitHub 上的仓库获取 HTML、CSS 和 JavaScript 文件,通过构建过程运行文件,然后发布网站。

你可以在 GitHub 的 github.io 域或自己的自定义域上托管站点。

什么是Hexo?

Hexo 是一个快速、简洁且高效的博客框架。Hexo 使用 Markdown(或其他渲染引擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。

配置环境准备

这里列出笔者的环境

  • Node.js 18.14.2
  • Git

安装Hexo

  • node.js 安装镜像在国外,我们这里更换国内淘宝镜像,执行npm config set registry https://registry.npm.taobao.org

  • 安装 hexo,执行 npm install -g hexo-cli

Hexo的初始化

  • 创建 Blog 文件夹,打开终端进入该目录
  • 打开 steam++ 加速 git clone
  • 执行 hexo init 初始化 Blog 文件夹
  • 执行 npm install 安装依赖包
  • 执行 hexo g 开始进行部署操作
  • 执行 hexo s 将生成的网页放在本地服务器
  • 打开浏览器,输入网址 http://localhost:4000/ 就可以看到本地的博客效果了
  • 效果没问题,返回终端按 Ctrl + C 中止服务运行

发布博客文章

  • 在blog路径下执行 hexo new "title"(title 为你的博客的标题),生成的.md文件路径在 blog\source\_posts下。

  • 打开 title.md ,编辑博客文件。

  • 关闭并保存,执行 hexo g 部署,执行 hexo s 发布,进入 http://localhost:4000/ 查看效果。

在Github上部署Hexo

  • 创建一个名为 username.github.io 的仓库,Github会自动识别为一个网站,其 url 就是 https://username.github.io

  • 复制仓库地址 https://github.com/username/username.github.io.git

  • 修改 Blog 文件夹里的 Blog/_config.yml

    • # Site
      title: "Tanphoon's Blog"
      subtitle: ''
      description: ''
      keywords:
      author: 'Tanphoon'
      language: en
      timezone: ''
      
    • # URL
      ## Set your site url here. For example, if you use GitHub Page, set url as 'https://username.github.io/project'
      url: https://xtf0214.github.io/
      permalink: :year/:month/:day/:title/
      permalink_defaults:
      pretty_urls:
        trailing_index: true # Set to false to remove trailing 'index.html' from permalinks
        trailing_html: true # Set to false to remove trailing '.html' from permalinks
      
    • # Deployment
      ## Docs: https://hexo.io/docs/one-command-deployment
      deploy:
      type: git
      repo: https://github.com/xtf0214/xtf0214.github.io
      branch: main
      
  • 执行 npm install hexo-deployer-git --save 安装 hexo-deployer-git

  • 执行 hexo g 部署,执行 hexo s 发布

  • 执行 hexo clean hexo d 生成站点文件并推送至远程库。

  • 登录 https://username.github.io 查看效果

参考资料

  • 文档 | Hexo

  • Github Pages搭建个人博客(最新版) - 简书 (jianshu.com)