hexo+github搭建博客

准备node.js和git

  • node.js : 直接官网下载

  • git : 直接官网下载

  • 验证安装结果 :

    1
    2
    3
    4
    $ node -v
    $ npm -v
    #npm是随同NodeJS一起安装的包管理工具,类似python的pip
    $ git --version

Github账户注册和新建项目

项目必须要遵守格式:uername.github.io,如下:

安装Hexo

  • Hexo 是一个快速、简洁且高效的博客框架。

    1
    2
    3
    4
    5
    $ mkdir blog && cd - #创建个人目录
    $ npm install -g hexo-cli #安装hexo
    $ hexo -v #检查hexo
    $ hexo init #初始化hexo
    $ npm install #安装所需包

Hexo与Github page关联

  • 设置Git的user name和email(如果是第一次的话)

    1
    2
    git config --global user.name  "xxx" git用户名
    git config --global user.email "xxx@xx.com" git邮箱
  • 生成密钥、公钥

    1
    2
    3
    4
    $ ssh-add -D
    $ rm -r ~/.ssh #删除存在的密钥、公钥
    $ ssh-keygen -t rsa -C "xxx@xx.com" #生成新密钥、公钥对应git邮箱
    $ cat ~/.ssh/id_rsa.pub #查看公钥内容
  • 添加公钥到github

    登陆github帐户,点击头像,然后 Settings -> 左栏点击 SSH and GPG keys -> 点击 New SSH key。然后复制上面的公钥内容,粘贴进“Key”文本域内。 title随便起个名字,点击 Add key完成。

  • 确认成功

    1
    2
    3
    4
    $ ssh -T xxx@github.com
    $ git remote -v
    origin https://github.com/someaccount/someproject.git (fetch)
    origin https://github.com/someaccount/someproject.git (push)

    git使用https协议,每次pull, push都会提示要输入密码,使用git协议,然后使用ssh密钥,这样免去每次都输密码的麻烦。

    SSH地址

    HTTPS地址

在_config.yml 进行基础配置

回到创建hexo的文件夹找到_config.yml,并编辑最后的信息:

1
2
3
4
5
deploy:
type: git
repository :git@github.com:flystar233/flystar233.github.io.git #发布不再需要密码
repository :https://github.com/flystar233/flystar233.github.io.git #发布需要密码
branch :master

让博客能加载图片

1
2
post_asset_folder: true #在_config.yml中将false改为true
$ npm install hexo-asset-image --save #在命令行中执行

这样之后,在运行hexo n "xxxx"来生成md博客时,/source/_posts文件夹内除了xxxx.md文件还有一个同名的文件夹。将博客所需图片放入此文件夹中,在md文件中(博客内容)插入图片时,使用命令 来插入图片,xxxx是文件名,路径不可有中文。

发布博客

在生成以及部署文章之前,需要安装一个扩展:

1
$ npm install hexo-deployer-git --save
  • 发布相关命令

    1
    2
    3
    4
    5
    6
    $ hexo clean # 清除全部文章
    $ hexo generate == hexo g #生成静态文件
    $ hexo deploy == hexo d #部署文件到github
    $ hexo new "文件名" #创建新文章
    $ hexo new page "页面名" #创建新页面
    $ hexo server #开启预览访问端口(默认端口4000,'ctrl + c'关闭server)
  • 查看博客

    部署成功后访问博客地址,如:flystar233.github.io