Windows下使用hexo搭建博客

根据下面的教程搭建的博客见这里

前言

马上要进入研究生了,不能再过浑浑噩噩的日子了,搭建一个小网站,用于记录自己所学的东西。其实,之前在腾讯云1元乞丐版上也搭建过博客,但是呢,只用来扯淡了。这次使用 GitHubPages 和 Hexo 建立自己的博客,希望能够促进自己成长。

下面先介绍为何选择 GitHubPages 和 Hexo 来搭建博客,然后介绍搭建博客的详细过程。

Why GitHub Pages and Hexo

因为 GitHub 的存在,我们得以简单快速地搭建个人博客。

GitHub
GitHub,是一个代码托管网站和社交编程网站。这里聚集了世界上各路技术牛叉的大牛,和最优秀的代码库。把你的博客托管在这里,还有什么不放心的呢O(∩_∩)O。

GitHub Pages
GitHub Pages,是用来托管 GitHub 上静态网页的免费站点,那 GitHub Pages具体有哪些功能呢:

  • 有足够的免费空间(1G),资料自己管理,保存可靠;
  • 享受 GitHub 的便利,上面有很多大牛,眼界会开阔很多;
  • 可以使用很多现成的博客框架,搭建过程简单快速。

HEXO

Hexo 是一个简单、快速、强大的静态博客框架,出自台湾大学生 tommy351 之手。我也看过使用 Jekyll、Octopress 搭建个人博客的过程,确实要繁琐许多。相比之下 Hexo 更轻便更快捷,下面是其官网强调的四大特点:

  1. 极速生成静态页面
  2. 一键部署博客
  3. 丰富的插件支持
  4. 支持 Markdown

相信大家对 GitHub Pages 和 Hexo 有了一定的了解,下面进入正题。

准备工作

注册 GitHub

访问 GitHub,注册十分简单,一定要记住注册时使用的邮箱,因为 GitHub 上很多通知都是通过邮箱的。如下图所示,框里有各种提示,这里就不多说了:

申请成功后,在 GitHub 官网上登录,并验证邮箱即可。

在 GitHub 上建立仓库

与 GitHub 建立好连接之后,就可以方便的使用它提供的 Pages 服务,GitHub Pages 分两种,一种是用你的 GitHub 用户名建立的 http://username.github.io 这样的用户&组织站点,另一种是依附项目的 Pages。

想建立个人博客是用的第一种,形如 http://username.github.io 这样的可访问的站点,每个用户名下面只能建立一个。

首先,点击右上角的+号,点击 New repository,新建一个仓库

然后,在Repository name,填写自己的用户名.github.io,例如我的用户名为zdaiot,则填写zdaiot.github.io

关于 Github 的使用,Crossin先生 也写了一篇通俗易懂的教程,大家可以去看看

极简 Github 上手教程

安装软件

Node.js

Node.js 下载

下载完成后根据提示一步一步安装就好,这个没有什么需要特别说明的。

安装git

git 下载

下载并安装下面两个软件,一直点击下一步即可。

配置 SSH

默认的cmd是没有ssh的,所以我们需要安装ssh:https://www.mls-software.com/opensshd.html 下载openssh,安装即可。

我们如何让本地 git 项目与远程的 GitHub 建立联系呢?方法是用 SSH。打开命令行,输入以下命令:

ssh -T [email protected]

如图:

如果是下面之类的反馈(或者显示 Hi xxx):

The authenticity of host 'github.com (207.97.227.239)' can't be established. RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48. Are you sure you want to continue connecting (yes/no)?

不用紧张,输入 yes 之后,看到下图的结果,就配置成功了。

但是,输入yes后,若提示如下图:

极大多数情况是由于github账号没有设置ssh公钥信息所致。 前往 GitHub 网站的"account settings"
依次点击"Setting -> SSH Keys"->“New SSH key”

Title处填写“id_rsa.pub”或其他任意信息。 key处原样拷贝下面命令的打印 ~/.ssh/id_rsa.pub 文件的内容:
如果没有该文件

ssh-keygen -t rsa

一路回车…

最后,输入

ssh -T [email protected]

确认OK即可。

安装Hexo

Hexo 安装

更改npm为国内镜像源:

npm config set registry https://registry.npm.taobao.org 
npm info underscore
(如果上面配置正确这个命令会有字符串response)

打开命令行,依次输入以下命令:

cd /
npm install hexo-cli -g

如图:

提示:cd / 作用是返回根目录,Git Shell 默认装在 C 盘,启动时默认路径为 C:\Users\xxx(用户名)\Documents\GitHub,输入 cd / 命令后就返回到了 C 盘根目录下,需不需要使用 cd / 看个人习惯(下同)

部署Hexo

Hexo 的部署可采用如下方法,输入命令:

hexo init [文件名]。

打开控制台,依次输入以下命令:

cd /
hexo init Hexo

回车后出现该提示则表示正确:

若报错,如下图:

则是因为环境变量设置的原因,如下所示,我们之前有个步骤是 cd /,所以路径如下:

添加系统环境变量如下:

添加成功后,即可运行 hexo 指令。

部署过程中,报错如下:

删除掉:C:\Users\<your username>\.config\configstore\insight-bower.yml,在我的这个文件夹下,只有一个文件update-notifier-npm.json,删除掉,在执行上述指令。

部署成功之后,Hexo 会自动在目标文件夹建立博客网站所需要的所有文件。此时可以通过输入以下命令在本地进行预览(在刚才创建的文件夹里):

C:\>cd /d C:\Hexo
hexo generate
hexo server

系统可能会出现提示,请点击允许。如下图所示则表示正确:

此时打开浏览器,在浏览器地址栏输入 http://localhost:4000/ (默认端口为4000), 便可以看到最原始的博客了。以后发表博文想先预览,也可以通过 hexo server 在本地先跑起来,看看效果。
效果如下图所示:

恭喜,到目前为止个人博客的雏形已经有了。

在 Git Shell 中按 Ctrl + C 并输入 y 可以停止该服务

将本地文件部署到 GitHub

** 修改 Hexo 中的 _config.yml 文件**
在 Hexo 文件夹下找到 _config.yml 文件,如下图所示:

找到其中的 deploy 标签,改成下图所示形式,并保存。注意:冒号后面要加上一个空格,否则会报错。

deploy:
  type: github
  repository: https://github.com/zdaiot/zdaiot.github.io.git
  branch: master

将其 deploy 到仓库中
打开 Git Shell 进入创建的文件夹,依次输入以下命令:

hexo clean
hexo generate
hexo deploy

如果出现下图错误,不要着急:

将deploy 的 type 改成 git,即改为:

deploy:
  type: git
  repository: https://github.com/zdaiot/zdaiot.github.io.git

然后再在 Git Shell 中运行以下命令:

npm install hexo-deployer-git --save

再重新来一遍:

hexo clean
hexo generate
hexo deploy

出现以下提示则表示正确:

但是,若报错提示:fatal: Not a git repository (or any of the parent directories): .git 提示说没有.git这样一个目录,则是因为上面没有安装git,就进行安装hexo,安装git软件,重新进行上面步骤

但是,若出现下面bug:

则,将 _config.yml 文件中配置改为:

deploy:
  type: git
  repository: [email protected]:zdaiot/zdaiot.github.io.git
  branch: master

恭喜,到这一步,个人博客就已经部署到 GitHub 上了,你可以到你的GitHub仓库查看是否已经更新。此时,通过
http://your_user_name.github.io
(即你那个仓库的名称,形如:“你的 GitHub 用户名”.http://github.io
就可以看到你的个人博客了。
若看不到,则参照下面的步骤,写一篇博客,发表上去!即可看到!
注意:这里可能会出现这种需要输入账号密码的情况

输入github的账号密码就可以了,记住那里输入密码的时候光标是不会移动的,只要你输入了就好,不要以为没输入上:)

安装Next主题

下载主题:
使用 Git Shell 进入 Hexo 文件夹,输入以下两条命令将主题下载到 theme/next文件夹下:

cd Hexo
git clone https://github.com/theme-next/hexo-theme-next.git themes/next

接着按照如下几个步骤进行:

  • 设置站点Hexo/_config.yml的theme字段值为next
  • 生成静态文件
hexo g
  • 开启服务,在本地查看效果
hexo s --debug
  • 同步代码到gitHub
hexo d

注:此时登录网站,发现是空白的,打开控制台,提示很多vendors目录下的文件404,解决办法是将next主题下即Hexo/themes/next/source下的vendors目录名改为lib,并修改Hexo/themes/next/_config.yml_internal: vendors改为_internal: lib

参考iissnan的回答

配置Next主题

风格配置

通过修改next主题下的_config.yml的scheme字段,配置不同的风格。

# Schemes
#scheme: Muse
#scheme: Mist
#scheme: Pisces
scheme: Gemini

本站点使用的是默认的Gemini,显示效果如下:

菜单设置

通过修改next主题下的_config.yml的menu字段,选定显示的菜单项。

menu:
  home: / || home
  about: /about/ || user
  tags: /tags/ || tags
  categories: /categories/ || th
  archives: /archives/ || archive
  #schedule: /schedule/ || calendar
  #sitemap: /sitemap.xml || sitemap
  #commonweal: /404/ || heartbeat

其中,home代表主页,categories代表分类页,about代表关于页面,archives代表归档页,commonweal代表404页面(page not found时候显示的页面)。

添加标签页面

前面通过修改next主题下的_config.yml文件中的menu选项,可以在主页面的菜单栏添加标签选项,但是此时点击标签,跳转的页面会显示page not found。

添加标签页面的具体方法是:
新建页面,输入如下命令:

cd Hexo
hexo new page tags

输入命令后,在Hexo/source下会新生成一个新的文件夹tags,在该文件夹下会有一个index.md文件。

设置页面类型,在上步新生成的Hexo/source/tags/index.md中添加type: “tags”,index.md文件内容如下:

---
title: tags
date: 2018-08-01 00:00:00
type: "tags"
---

设置具体文章的tags
当要为某一篇文章添加标签,只需在Hexo/source/_post目录下的具体文章的tags中添加标签即可,如:

---
title: 基于Hexo和Github搭建博客
date: 2018-08-01
tags: [npm, hexo, github]
categories: 搭建博客
---

本站添加为标签后的效果如下:

添加分类标签

步骤与添加标签页面类似,具体如下:

新建页面,输入如下命令:

cd Hexo
hexo new page categories

输入命令后,在Hexo/source下会新生成一个新的文件夹categories,在该文件夹下会有一个index.md文件。
设置页面类型

在上步新生成的Hexo/source/categories/index.md中添加type: “categories”,index.md文件内容如下:

---
title: categories
date: 2018-08-01 00:00:00
type: "categories"
---

设置具体文章的categories
当要为某一篇文章添加分类,只需在Hexo/source/_post目录下的具体文章的categories中添加分类即可,如:

---
title: 基于Hexo和Github搭建博客
date: 2016-11-09
tags: [npm, hexo, github]
categories: 搭建博客
---

本站添加为标签后的效果如下:

添加我的页面

步骤与添加标签页面类似,具体如下:

新建页面

cd Hexo
hexo new page about

输入命令后,在Hexo/source下会新生成一个新的文件夹about,在该文件夹下会有一个index.md文件。
修改about/index.md,本站点index.md如下

---
title: about
date: 2018-08-01 00:00:00
---
## 关于我
一只学AI的小菜鸟,欢迎分享知识。
From zdaiot
QQ:972392704
Email: [email protected]

效果如下:

语言设置

若想显示为中文,需要在Hexo根目录下的_config.yml 文件修改,而Next主题下的_config.yml 文件不需要想应的修改

language: zh-CN

菜单项文本修改是在对next主题下的language文件夹下的文件进行修改,若当前语言是简体中文,直接修改language/zh-CN.yml里的对应字段即可。
本站点显示主页,分类页,关于页面和归档页。

头像设置

打开头像

  • 打开themes/next下的_config.yml文件,搜索 Sidebar Avatar关键字,去掉url后面的#
# Sidebar Avatar
# Sidebar Avatar
avatar:
  # in theme directory(source/images): /images/avatar.gif
  # in site  directory(source/uploads): /uploads/avatar.gif
  # You can also use other linking images.
  url: http://example.com/avatar.png
  • 或者使用本地图片,在next/source/images/下放置头像文件avatar.gif,更改avatar
# Sidebar Avatar
avatar:
  # in theme directory(source/images): /images/avatar.gif
  # in site  directory(source/uploads): /uploads/avatar.gif
  # You can also use other linking images.
  url: /images/avatar.gif

设置头像边框为圆形框并旋转

打开\themes\next\source\css\_common\components\sidebar\sidebar-author.styl,在里面更改添加如下代码:

.site-author-image {
  display: block;
  margin: 0 auto;
  padding: $site-author-image-padding;
  max-width: $site-author-image-width;
  height: $site-author-image-height;
  border: $site-author-image-border-width solid $site-author-image-border-color;

  /* 头像圆形 */
  border-radius: 80px;
  -webkit-border-radius: 80px;
  -moz-border-radius: 80px;
  box-shadow: inset 0 -1px 0 #333sf;

  /* 设置循环动画 [animation: (play)动画名称 (2s)动画播放时长单位秒或微秒 (ase-out)动画播放的速度曲线为以低速结束 
    (1s)等待1秒然后开始动画 (1)动画播放次数(infinite为循环播放) ]*/


  /* 鼠标经过头像旋转360度 */
  -webkit-transition: -webkit-transform 1.0s ease-out;
  -moz-transition: -moz-transform 1.0s ease-out;
  transition: transform 1.0s ease-out;
}

img:hover {
  /* 鼠标经过停止头像旋转 
  -webkit-animation-play-state:paused;
  animation-play-state:paused;*/

  /* 鼠标经过头像旋转360度 */
  -webkit-transform: rotateZ(360deg);
  -moz-transform: rotateZ(360deg);
  transform: rotateZ(360deg);
}

/* Z 轴旋转动画 */
@-webkit-keyframes play {
  0% {
    -webkit-transform: rotateZ(0deg);
  }
  100% {
    -webkit-transform: rotateZ(-360deg);
  }
}
@-moz-keyframes play {
  0% {
    -moz-transform: rotateZ(0deg);
  }
  100% {
    -moz-transform: rotateZ(-360deg);
  }
}
@keyframes play {
  0% {
    transform: rotateZ(0deg);
  }
  100% {
    transform: rotateZ(-360deg);
  }
}

头像下方文字和作者设置

打开Hexo下的_config.yml文件

# Site
title: zdaiot
subtitle: QS的大西瓜
description: QS的大西瓜
keywords: QS的大西瓜
author: zdaiot
language: zh-CN
timezone:

新建404界面

  • 在站点根目录下,输入 hexo new page 404,默认在Hexo 站点/source/404/index.md
  • 打开新建的404界面,在顶部插入一行,写上permalink: /404,这表示指定该页固定链接为 http://"主页"/404.html
---
title: 404-找不到页面
date: 2016-05-21 18:53:59
comments: false
permalink: /404
---
<center>404 Not Found<center>
-------
<center>**对不起,您所访问的页面不存在或者已删除**
你可以**[点击此处](http://www.zdaiot.com)**返回首页。
你也可以<a href="#" class="popup-trigger">**点击此处**</a>重新搜索结果。</center>
![网站二维码](/images/website.png)<center>扫一扫,用手机访问本站<center>
  • 如果你不想编辑属于自己的404界面,可以显示腾讯公益404界面,代码如下:
<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8;"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="robots" content="all" />
  <meta name="robots" content="index,follow"/>
  <link rel="stylesheet" type="text/css" href="https://qzone.qq.com/gy/404/style/404style.css">
</head>
<body>
  <script type="text/plain" src="http://www.qq.com/404/search_children.js"
          charset="utf-8" homePageUrl="/"
          homePageName="回到我的主页">
  </script>
  <script src="https://qzone.qq.com/gy/404/data.js" charset="utf-8"></script>
  <script src="https://qzone.qq.com/gy/404/page.js" charset="utf-8"></script>
</body>
</html>

设置网站的图标Favicon

实现效果图

并且修改themes/next下的_config.yml文件中,代码如下:

# For example, you put your favicons into `hexo-site/source/images` directory.
# Then need to rename & redefine they on any other names, otherwise icons from Next will rewrite your custom icons in Hexo.
favicon:
  small: /images/favicon-16x16-next.png
  medium: /images/favicon-32x32-next.png
  apple_touch_icon: /images/apple-touch-icon-next.png
  safari_pinned_tab: /images/logo.svg
  #android_manifest: /images/manifest.json
  #ms_browserconfig: /images/browserconfig.xml

EasyIcon中找一张图标,或者去别的网站下载或者制作,要求按照代码中的大小与格式。并将图标名称改为代码中的名字,然后把图标放在/themes/next/source/images

显示返回顶部按钮

设置侧边栏,显示返回顶部按钮,及百分比。若要显示在右下角,则b2t: false

# Back to top in sidebar (only for Pisces | Gemini).
b2t: true

# Scroll percent label in b2t button.
scrollpercent: true

开启订阅微信公众号

效果如下:

将微信公众号的图片放到next/source/uploads/文件夹中,若没有该文件夹,新建即可,并把图片重命名为wechat-qcode.jpg

在主题配置文件中,找到wechat_subscriber,设置为:

wechat_subscriber:
  enabled: true
  qcode: /uploads/wechat-qcode.jpg
  description: 欢迎您扫一扫上面的微信公众号,订阅我的博客!

添加顶部加载条

打开themes/next下的_config.yml,搜索关键字pace,设置为true,可以更换加载样式

# Progress bar in the top during page loading.
pace: true
# Themes list:
#pace-theme-big-counter
#pace-theme-bounce
#pace-theme-barber-shop
#pace-theme-center-atom
#pace-theme-center-circle
#pace-theme-center-radar
#pace-theme-center-simple
#pace-theme-corner-indicator
#pace-theme-fill-left
#pace-theme-flash
#pace-theme-loading-bar
#pace-theme-mac-osx
#pace-theme-minimal
# For example
# pace_theme: pace-theme-center-simple
pace_theme: pace-theme-flash #替换更换样式

然后,将 https://github.com/iissnan/hexo-theme-next/tree/master/source/lib/pace 中的所有文件放到hexo\themes\next\source\lib\pace文件夹中

修改文章底部的那个带#号的标签

实现效果图

修改模板/themes/next/layout/_macro/post.swig,搜索 rel="tag">#,将 # 换成<i class="fa fa-tag"></i>

修改文章内文本连接样式

打开 themes/next/source/css/_custom/下的custom.styl,添加代码

// 文章内链接文本样式
.post-body p a{
  color: #0593d3;
  border-bottom: none;
  border-bottom: 1px solid #0593d3;
  &:hover {
    color: #fc6423;
    border-bottom: none;
    border-bottom: 1px solid #fc6423;
  }
}

主页文章添加阴影效果

打开\themes\next\source\css\_custom\custom.styl,向里面加入:

 // Custom styles.
// 主页文章添加阴影效果
 .post {
   margin-top: 60px;
   margin-bottom: 60px;
   padding: 25px;
   -webkit-box-shadow: 0 0 5px rgba(202, 203, 203, .5);
   -moz-box-shadow: 0 0 5px rgba(202, 203, 204, .5);
  }

文章顶部显示更新时间

打开主题配置文件_config.yml,搜索关键字updated_at设置为true

# Post meta display settings
post_meta:
  item_text: true
  created_at: true
  updated_at:
    enabled: true
    # If true, show updated date label only if `updated date` different from 'created date' (post edited in another day than was created).
    # And if post will edited in same day as created, edited time will show in popup title under created time label.
    # If false show anyway, but if post edited in same day, show only edited time.
    another_day: true
  categories: true

编辑文章,增加关键字updated

---
title: https://www.zdaiot.com/%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/Windows%E4%B8%8B%E4%BD%BF%E7%94%A8hexo%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/
date: 2018-07-29 21:12:14
updated: 2017-7-30 18:18:54 #手动添加更新时间
tags:
copyright: true
---

侧边栏设置

设置侧边栏社交链接

  • 打开themes/next下的_config.yml文件,搜索关键字social,然后添加社交站点名称与地址即可。
# Social links
social:
  GitHub: https://github.com/your-user-name
  Twitter: https://twitter.com/your-user-name
  Weibo: https://weibo.com/your-user-name
  douban: https://douban.com/people/your-user-name
  zhihu: https://www.zhihu.com/people/your-user-name
  # 等等

设置侧边栏社交图标

  • 打开themes/next下的_config.yml文件,搜索关键字social_icons,添加社交站点名称(注意大小写)图标,Font Awesome图标地址,注意知乎没有对应的图标,可以直接更改为别的图标
social_icons:
  enable: true
  # Icon Mappings.
  # KeyMapsToSocalItemKey: NameOfTheIconFromFontAwesome
  GitHub: github
  Twitter: twitter
  Weibo: weibo
  Linkedin: linkedin

上述设置侧边栏社交链接与社交图标还可以直接更改Social links,不需要更改social_icons,例如:

social:
  GitHub: https://github.com/zdaiot || github
  E-Mail: mailto:[email protected] || envelope
  知乎: https://www.zhihu.com/people/zdaiot || book
  CSDN: https://blog.csdn.net/zdaiot || copyright

RSS

  • 在你Hexo 站点目录下
npm install hexo-generator-feed --save
  • 打开Hexo 站点下的_config.yml,在Extensions中添加如下配置
# Extensions
plugin: hexo-generator-feed
# feed
# Dependencies: https://github.com/hexojs/hexo-generator-feed
feed:
  type: atom
  path: atom.xml
  limit: 20
  hub:
  content::
  • 在主题配置文件themes/next/_config.yml文件中,搜索rss,更改为:
rss: /atom.xml

点击rss后,出现:

友情链接

  • 打开themes/next下的_config.yml文件,搜索关键字Blog rolls
# Blog rolls
links_title: 友情链接 #标题
links_layout: block #布局,一行一个连接
#links_layout: inline
links: #连接
  baidu: http://example.com/
  google: http://example.com/

添加百度分享

因为next\layout_partials\share\baidushare.swig文件中代码显示:

{% if theme.baidushare.type === "button" %}
...
...
{% elseif theme.baidushare.type === "slide" %}
...

在配置百度分享功能时需指定其type,所以将主题配置_config.yml文件中关于baidushare部分的内容改为(其中type亦可以选择button):

baidushare:
  type: slide
  baidushare: true

_config.yml中提示:Warning: Baidu Share does not support https.
因为百度分享不支持在https上使用,所以一种解决方法便是,直接放文件到我们自己的目录下面。

访问链接: static文件夹
下载压缩包到本地,解压后,将static文件夹保存至themes\next\source目录下。
修改文件:themes\next\layout\_partials\share\baidushare.swig
将文件 末尾 部分的代码进行修改:

.src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];

改为:

.src='/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];

添加AddThis分享

我选择的是AddThis作为博客的第三方分享。AdThis是国外的第三方分享,使用方便,可以用google直接登录。能自定义分享样式

注册AddThis,选择分享按钮:

选择显示样式(Select a Tool Type),AddThis提供了7种显示样式,你可以更加左边菜单栏点击,右边会自动显示你选择的相应样式。值得注意的是。在其右上角可以切换PCPhone显示

点击Continue配置分享按钮,注意:不同的风格样式,配置方式不同

配置完成后 , 获取代码ID , 在js代码中获取pubid后面的ID

编辑主题配置文件themes/next/_config.yml, 找到关键字add_this_id, 添加pubid

设置文章代码主题

Next主题总共支持5种主题,默认主题是白色的normal。通过修改next主题下的_config.yml的highlight字段,来设置代码主题。
本站点使用的是normal主题。即令highlight为normal。

渲染 MathJax 数学公式

Hexo 默认使用 hexo-renderer-marked 引擎渲染网页,该引擎会把一些特殊的 markdown 符号转换为相应的 html 标签,比如在 markdown 语法中,下划线_代表斜体,会被渲染引擎处理为<em>标签。

因为类 Latex 格式书写的数学公式下划线_表示下标,有特殊的含义,如果被强制转换为<em>标签,那么 MathJax 引擎在渲染数学公式的时候就会出错。

类似的语义冲突的符号还包括*, {, }, \\等。

解决方法

首先开启next主题对MathJax的支持,找到next\ _config.yml文件,把 math 默认的 false 修改为true

# Math Equations Render Support
math:
enable: true

# Default(true) will load mathjax/katex script on demand
# That is it only render those page who has 'mathjax: true' in Front Matter.
# If you set it to false, it will load mathjax/katex srcipt EVERY PAGE.
per_page: true

在需要MathJax渲染的文章前面添加

mathjax: true

也可以直接在/scaffolds/post.md文件中添加:

---
title: {{ title }}
date: {{ date }}
tags:
categories:
copyright:
mathjax:
---

这样每次hexo new "你的内容"之后,生成的md文件会自动把mathjax:加到里面

更换 Hexo 的 markdown 渲染引擎,hexo-renderer-kramed 引擎是在默认的渲染引擎 hexo-renderer-marked 的基础上修改了一些 bug ,两者比较接近,也比较轻量级。

npm uninstall hexo-renderer-marked --save
npm install hexo-renderer-kramed --save

执行上面的命令即可,先卸载原来的渲染引擎,再安装新的。
然后,跟换引擎后行间公式可以正确渲染了,但是这样还没有完全解决问题,行内公式的渲染还是有问题,因为 hexo-renderer-kramed 引擎也有语义冲突的问题。接下来到博客根目录下,找到node_modules\kramed\lib\rules\inline.js,把第11行的 escape 变量的值做相应的修改:

  //escape: /^\\([\\`*{}\[\]()#$+\-.!_>])/,
  escape: /^\\([`*\[\]()#$+\-.!_>])/,

这一步是在原基础上取消了对,{,}的转义(escape)。
同时把第20行的em变量也要做相应的修改。

  //em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
  em: /^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,

重新启动hexo(先clean再generate),问题完美解决。哦,如果不幸还没解决的话,看看是不是还需要在使用的主题中配置mathjax开关。

首页显示文章标题,而非全文

进入hexo博客项目的themes/next/_config.yml文件,搜索"auto_excerpt",找到如下部分:

# Automatically Excerpt. Not recommand.
# Please use <!-- more --> in the post to control excerpt accurately.
auto_excerpt:
  enable: false
  length: 150

把enable改为对应的false改为true,然后

hexo d -g

再进主页,问题就解决了!

在右上角或者左上角实现fork me on github

实现效果图:

点击这里 或者 这里挑选自己喜欢的样式,并复制代码。 例如,我是复制如下代码:

<a href="https://your-url" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

然后粘贴刚才复制的代码到themes/next/layout/_layout.swig文件中(放在<div class="headband"></div>的下面),并把href改为你的github地址

在网站底部加上访问量与字数统计

方法一

实现效果图

打开\themes\next\layout\_partials\footer.swig文件,在copyright前加上这句话:

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

然后在下面添加显示统计的代码

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>

在这里有两中不同计算方式的统计代码:

  1. pv的方式,单个用户连续点击n篇文章,记录n次访问量
<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
  1. uv的方式,单个用户连续点击n篇文章,只记录1次访客数
<span id="busuanzi_container_site_uv">
  本站总访问量<span id="busuanzi_value_site_uv"></span>次
</span>

添加之后再执行hexo d -g,然后再刷新页面就能看到效果

方法二

以上方法无法统计字数,采用如下方法,打开\themes\next\layout\_partials\footer.swig文件,在copyright前加上:

<!-- 新增访客统计代码 -->

<div class="busuanzi-count">
    <script async="" src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="site-uv">
      <i class="fa fa-user"></i>
      访问用户: <span class="busuanzi-value" id="busuanzi_value_site_uv"></span> 人
    </span>
    <div class="powered-by"></div>
    <span class="site-uv">
      <i class="fa fa-eye"></i>
      访问次数: <span class="busuanzi-value" id="busuanzi_value_site_pv"></span> 次
    </span>
    <!-- 博客字数统计 -->
    <span class="site-pv">
      <i class="fa fa-pencil"></i>
      博客全站共: <span class="post-count">{{ totalcount(site) }}</span> 字
    </span>
</div>
<!-- 新增访客统计代码 END-->

添加之后再执行hexo d -g,然后再刷新页面就能看到效果

实现统计功能

实现效果图

在根目录下安装 hexo-symbols-count-time,运行:

npm install hexo-symbols-count-time --save

然后在主题的配置文件next/_config.yml中,配置如下:

# Post wordcount display settings
# Dependencies: https://github.com/theme-next/hexo-symbols-count-time
symbols_count_time:
  separated_meta: true
  item_text_post: true
  item_text_total: false
  awl: 4
  wpm: 275

最后在,hexo/_config.yml中,添加:

symbols_count_time:
  symbols: true
  time: true
  total_symbols: true
  total_time: true

隐藏网页底部powered By Hexo / 强力驱动

打开themes/next/layout/_partials/footer.swig,使用<!---->隐藏之间的代码即可,或者直接删除。位置如图:

在底部添加网站运行时间

打开themes/next/layout/_partials/footer.swig,在最下面添加代码

<!-- 在网页底部添加网站运行时间 -->
<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
<script>
    var now = new Date();
    function createtime() {
        var grt= new Date("08/01/2018 00:00:00");//此处修改你的建站时间或者网站上线时间
        now.setTime(now.getTime()+250);
        days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days);
        hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours);
        if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
        mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;}
        seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
        snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;}
        document.getElementById("timeDate").innerHTML = "Run for "+dnum+" Days ";
        document.getElementById("times").innerHTML = hnum + " Hours " + mnum + " m " + snum + " s";
    }
setInterval("createtime()",250);
</script>

在文章底部增加版权信息

实现效果图

在目录 next/layout/_macro/下添加 my-copyright.swig

{% if page.copyright %}
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="{{ url_for(page.path) }}">{{ page.title }}</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 {{ theme.author }} 的个人博客">{{ theme.author }}</a></p>
  <p><span>发布时间:</span>{{ page.date.format("YYYY年MM月DD日 - HH:MM") }}</p>
  <p><span>最后更新:</span>{{ page.updated.format("YYYY年MM月DD日 - HH:MM") }}</p>
  <p><span>原始链接:</span><a href="{{ url_for(page.path) }}" title="{{ page.title }}">{{ page.permalink }}</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="{{ page.permalink }}"  aria-label="复制成功!"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>
{% endif %}

在目录next/source/css/_common/components/post/下添加my-post-copyright.styl

.my_post_copyright {
  width: 85%;
  max-width: 45em;
  margin: 2.8em auto 0;
  padding: 0.5em 1.0em;
  border: 1px solid #d3d3d3;
  font-size: 0.93rem;
  line-height: 1.6em;
  word-break: break-all;
  background: rgba(255,255,255,0.4);
}
.my_post_copyright p{margin:0;}
.my_post_copyright span {
  display: inline-block;
  width: 5.2em;
  color: #b5b5b5;
  font-weight: bold;
}
.my_post_copyright .raw {
  margin-left: 1em;
  width: 5em;
}
.my_post_copyright a {
  color: #808080;
  border-bottom:0;
}
.my_post_copyright a:hover {
  color: #a3d2a3;
  text-decoration: underline;
}
.my_post_copyright:hover .fa-clipboard {
  color: #000;
}
.my_post_copyright .post-url:hover {
  font-weight: normal;
}
.my_post_copyright .copy-path {
  margin-left: 1em;
  width: 1em;
  +mobile(){display:none;}
}
.my_post_copyright .copy-path:hover {
  color: #808080;
  cursor: pointer;
}

修改next/layout/_macro/post.swig,在代码

{% if theme.wechat_subscriber.enabled and not is_index %}
  <div>
  {% include 'wechat-subscriber.swig' %}
  </div>
{% endif %}

加入代码

<div>
      {% if not is_index %}
        {% include 'my-copyright.swig' %}
      {% endif %}
</div>

如图所示:

修改next/source/css/_common/components/post/post.styl文件,在最后一行增加代码:

@import "my-post-copyright"

保存重新生成即可。

如果要在该博文下面增加版权信息的显示,需要在 Markdown 中增加copyright: true的设置,类似:

---
title: https://www.zdaiot.com/%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/Windows%E4%B8%8B%E4%BD%BF%E7%94%A8hexo%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/
date: 2018-07-29 21:12:14
tags:
copyright: true
---

小技巧:如果你觉得每次都要输入copyright: true很麻烦的话,那么在/scaffolds/post.md文件中添加:

---
title: {{ title }}
date: {{ date }}
tags:
categories:
copyright:
---

这样每次hexo new "你的内容"之后,生成的md文件会自动把copyright:加到里面去,同理也会把categories:加进入
(注意:如果解析出来之后,你的原始链接有问题:如:http://yoursite.com/2018/07/29/https://www.zdaiot.com/%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/Windows%E4%B8%8B%E4%BD%BF%E7%94%A8hexo%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2//,那么在根目录下_config.yml中写成类似这样:)

就行了。

文章加密访问

Next V6.0之前

实现效果图

打开themes/next/layout/_partials/head.swig文件,在以下位置插入这样一段代码:

<script>
    (function(){
        if('{{ page.password }}'){
            if (prompt('请输入文章密码') !== '{{ page.password }}'){
                alert('密码错误!');
                history.back();
            }
        }
    })();
</script>

然后在文章上写成类似这样:

Next V6.0之后

点击这里查看详情

在 hexo 根目录的 package.json 中添加
"hexo-blog-encrypt": "1.1.*"依赖。

执行下面命令,该插件会自动安装:

npm install

首先在 _config.yml 中启用该插件:

# Security
##
encrypt:
    enable: true

然后在你的文章的头部添加上对应的字段,如 password, abstract, message

---
title: hello world
date: 2016-03-30 21:18:02
tags:
    - fdsafsdaf
password: Mike
abstract: Welcome to my blog, enter password to read.
message: Welcome to my blog, enter password to read.
---
  • password: 是该博客加密使用的密码
  • abstract: 是该博客的摘要,会显示在博客的列表页
  • message: 这个是博客查看时,密码输入框上面的描述性文字

如果你想对 TOC 也进行加密。如果你有一篇文章使用了 TOC,你需要修改模板的部分代码。这里用 landscape 作为例子:

  • 你可以在 _hexo/themes/landscape/layout/partial/article.ejs 找到 article.ejs。
  • 然后找到 <% post.content %> 这段代码,通常在30行左右。
  • 使用如下的代码来替代它:
    <% if(post.toc == true){ %>
        <div id="toc-div" class="toc-article" <% if (post.encrypt == true) { %>style="display:none" <% } %>>
            <strong class="toc-title">Index</strong>
            <% if (post.encrypt == true) { %>
                <%- toc(post.origin) %>
            <% } else { %>
                <%- toc(post.content) %>
            <% } %>
        </div>
    <% } %>
    <%- post.content %>

添加gitalk评论系统

gitalk:一个基于 Github Issue 和 Preact 开发的评论插件
详情Demo可见:https://gitalk.github.io/
在GitHub上注册新应用,链接:https://github.com/settings/applications/new

参数说明:
Application name: # 应用名称,随意
Homepage URL: # 网站URL,如http://www.zdaiot.com
Application description # 描述,随意
Authorization callback URL:# 网站URL,http://www.zdaiot.com

点击注册后,页面跳转如下,其中Client IDClient Secret在后面的配置中需要用到,到时复制粘贴即可:

新建/layout/_third-party/comments/gitalk.swig文件,并添加内容:

{% if page.comments && theme.gitalk.enable %}
  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: '{{ theme.gitalk.ClientID }}',
          clientSecret: '{{ theme.gitalk.ClientSecret }}',
          repo: '{{ theme.gitalk.repo }}',
          owner: '{{ theme.gitalk.githubID }}',
          admin: ['{{ theme.gitalk.adminUser }}'],
          id: location.pathname,
          distractionFreeMode: '{{ theme.gitalk.distractionFreeMode }}'
        })
        gitalk.render('gitalk-container')
       </script>
{% endif %}

修改/layout/_partials/comments.swig,添加内容如下,与前面的elseif同一级别上:

{% elseif theme.gitalk.enable %}
  <div id="gitalk-container"></div>

具体位置如下图所示:

修改layout/_third-party/comments/index.swig,在最后一行添加内容:

{% include 'gitalk.swig' %}

新建/source/css/_common/components/third-party/gitalk.styl文件,添加内容:

.gt-header a, .gt-comments a, .gt-popup a
  border-bottom: none;
.gt-container .gt-popup .gt-action.is--active:before
  top: 0.7em;

修改/source/css/_common/components/third-party/third-party.styl,在最后一行上添加内容,引入样式:

@import "gitalk";

在主题配置文件next/_config.yml中添加如下内容:

gitalk:
  enable: true
  ClientID: 4800250e682fe873198b
  ClientSecret: 80f7f33f5f8ddfd3944f455cabadda4ff3299147
  repo: zdaiot.github.io   # 例:zdaiot.github.io
  adminUser: zdaiot #指定可初始化评论账户
  githubID: zdaiot
  distractionFreeMode: true

同步到github后,打开具体某一篇文章,如下图所示,提示,联系@zdaiot初始化创建。如下下面设置均未出错,等待即可,大约几天后,就会出现评论框~~~~

则可在主题配置文件next/_config.yml中改为添加如下内容:

gitalk:
  enable: true
  ClientID: 4800250e682fe873198b
  ClientSecret: 80f7f33f5f8ddfd3944f455cabadda4ff3299147
  repo: zdaiot.github.io   # 例:zdaiot.github.io
  adminUser: zdaiot #指定可初始化评论账户
  githubID: zdaiot
  distractionFreeMode: true

此时,若出现,Error:Not Found,可试试连接手机热点,更换IP地址。

以上就是NexT中添加gitalk评论的配置,博客上传到GitHub上后,打开页面进入某一博客内容下,就可看到评论处。

若想查看该github应用,点击网址https://github.com/settings/developers 如下图所示

为了解决label不能超过50而引起的Error: Validation Failed.问题,这里需要将 https://github.com/blueimp/JavaScript-MD5/blob/master/js/md5.min.js 中的内容保存在本地的Hexo\themes\next\source\js\src文件夹中,然后更改/layout/_third-party/comments/gitalk.swig

{% if page.comments && theme.gitalk.enable %}
  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
  <script src="/js/src/md5.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: '{{ theme.gitalk.ClientID }}',
          clientSecret: '{{ theme.gitalk.ClientSecret }}',
          repo: '{{ theme.gitalk.repo }}',
          owner: '{{ theme.gitalk.githubID }}',
          admin: ['{{ theme.gitalk.adminUser }}'],
          id: md5(location.pathname),
          distractionFreeMode: '{{ theme.gitalk.distractionFreeMode }}'
        })
        gitalk.render('gitalk-container')
    </script>
{% endif %}

接入网页在线联系功能

首先在DaoVoice注册个账号,我的邀请码是0f81ff2f

完成后,会得到一个app_id,后面会用到:

修改/themes/next/layout/_partials/head/head.swig文件,添加内容如下:

{% if theme.daovoice %}
  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "{{theme.daovoice_app_id}}"
    });
  daovoice('update');
  </script>
{% endif %}

next/_config.yml文件中添加内容:

# Online contact
daovoice: true
daovoice_app_id:   # 这里填你刚才获得的 app_id

使用微信接受消息,如图,首先在DaoVoce控制台,点击对话->我

点击右上角的个人设置

点击绑定微信,这里我的已经绑定过了

设置->应用设置->聊天设置下拉可以找到自定义位置等

添加打赏功能

准备支付宝和微信二维码

  • 微信是在收付款->二维码收款->保存收款码
  • 支付宝是在收钱->保存图片

next/_config.yml中配置图片

reward_comment: 坚持原创技术分享,您的支持将鼓励我继续创作!
wechatpay: /images/wechat.png
alipay: /images/aipay.jpg

wechat.jpg、aipay.png图片放入themes/next/source/images中

修改next/source/css/_common/components/post/post-reward.styl,注释wechat:hoveralipay:hover

/* 注释文字闪动函数
#wechat:hover p{
    animation: roll 0.1s infinite linear;
    -webkit-animation: roll 0.1s infinite linear;
    -moz-animation: roll 0.1s infinite linear;
}
#alipay:hover p{
    animation: roll 0.1s infinite linear;
    -webkit-animation: roll 0.1s infinite linear;
    -moz-animation: roll 0.1s infinite linear;
}
*/

对于next 6.0.0以上版本,更改为如下:

#rewardButton {
    cursor: pointer;
    border: 0;
    outline: 0;
    border-radius: 5px;
    padding: 0;
    margin: 0;
    letter-spacing: normal;
    text-transform: none;
    text-indent: 0px;
    text-shadow: none;
}
#rewardButton span {
    display: inline-block;
    width: 80px;
    height: 35px;
    border-radius: 5px;
    color: #fff;
    font-weight: 400;
    font-style: normal;
    font-variant: normal;
    font-stretch: normal;
    font-size: 18px;
    font-family: "Microsoft Yahei";
    background: #F44336;
}
#rewardButton span:hover{
    background: #F7877F;
}
#QR{
    padding-top:20px;
}
#QR a{
    border:0;
}
#QR img{
    width: 180px;
    max-width: 100%;
    display: inline-block;
    margin: 0.8em 2em 0 2em;
}

/* 注释文字闪动函数
#wechat:hover p{
    animation: roll 0.1s infinite linear;
    -webkit-animation: roll 0.1s infinite linear;
    -moz-animation: roll 0.1s infinite linear;
}
#alipay:hover p{
    animation: roll 0.1s infinite linear;
    -webkit-animation: roll 0.1s infinite linear;
    -moz-animation: roll 0.1s infinite linear;
}
*/

#bitcoin:hover p {
    animation: roll 0.1s infinite linear;
    -webkit-animation: roll 0.1s infinite linear;
    -moz-animation: roll 0.1s infinite linear;
}
@keyframes roll {
    from {
      transform(rotateZ(30deg));
    }
    to {
      transform(rotateZ(-30deg));
    }
}

效果如图:

资源文件夹

有两种方法,第一种是不用插件的情况,第二种是使用一种hexo的插件。

无论哪种方法都有一个共同的前提:修改hexo/_config.yml配置文件post_asset_folder项为true

创建博客是使用命令创建:

hexo new [layout] <title>

其中的layout项可以省略,例如:

hexo new "这是一个新的博客"

使用完命令之后,在source/_post文件夹里面就会出现一个“这是一个新的博客.md”的文件和一个“这是一个新的博客”的文件夹。

下一步就是把需要的图片放到新创建的那个文件夹里面去。

  • 引用图片的第一种方法
{% asset_img 这是一个新的博客的图片.jpg 这是一个新的博客的图片的说明 %}

用此种方法,而不是以前的![]()方法,前提是你的hexo的版本是hexo3以上,到package.json里面看一下吧。如果不是hexo3以上的版本,那就只能用第二种方法了。

将为知笔记的引用图片方式转为该方式代码为:

# -*- coding: UTF-8 -*-
import re

path = u'./https://www.zdaiot.com/%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/Windows%E4%B8%8B%E4%BD%BF%E7%94%A8hexo%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/.md'

with open(path, 'r', encoding='UTF-8') as f:
    content = f.readlines()
f.close()

for index, x in enumerate(content):
    match_result = re.match(r'!\[(.*)\]\((.*)\)', x)
    if match_result:
        pic_path = match_result.group(2)
        pic_name = pic_path.split('/')[1]

        if match_result.group(1):
            new_pic_path = '{' + '% asset_img {} {} %'.format(pic_name, match_result.group(1)) + '}' + '\n'
        else:
            new_pic_path = '{' + '% asset_img {} %'.format(pic_name) + '}' + '\n'

        print(new_pic_path)
        content[index] = new_pic_path

fp = open(path, 'w', encoding='UTF-8')
for x in content:
    fp.write(x)
fp.close()
  • 下面是第二种方法,hexo插件的方法

这是插件的链接

安装

npm install hexo-asset-image --save

之后就可以按照正常的方法使用的,例如

![](https://www.zdaiot.com/%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/Windows%E4%B8%8B%E4%BD%BF%E7%94%A8hexo%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2//1.png)

将为知笔记的引用图片方式转为该方式代码为

# -*- coding: UTF-8 -*-
import re

path = u'https://www.zdaiot.com/%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/Windows%E4%B8%8B%E4%BD%BF%E7%94%A8hexo%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/.md'
path_ = path[:-3]

with open(path, 'r', encoding='UTF-8') as f:
    content = f.readlines()
f.close()

for index, x in enumerate(content):
    match_result = re.match(r'!\[(.*)\]\((.*)\)', x)
    if match_result:
        pic_path = match_result.group(2)
        pic_name = pic_path.split('/')[1]

        if match_result.group(1):
            new_pic_path = '![' + '{}'.format(match_result.group(1)) + ']' + '({}'.format(path_) + '/{})'.format(pic_name) +'\n'
        else:
            new_pic_path = '![]' + '({}'.format(path_) + '/{})'.format(pic_name) +'\n'

        print(new_pic_path)
        content[index] = new_pic_path

fp = open(path, 'w', encoding='UTF-8')
for x in content:
    fp.write(x)
fp.close()

需要注意的是,这两种方法不能同时使用,否则的话路径会重复。解决方法为删除hexo-asset-image文件夹

加入站点内容搜索功能

本站点使用的是Local Search。加入站点内容搜索功能步骤如下:

安装hexo-generator-searchdb

npm install hexo-generator-searchdb --save

注意:安装时应在站点根目录下,即Hexo目录下
添加search字段,在站点Hexo/_config.ymlExtensions下面添加search字段,如下:

search:
  path: search.xml
  field: post
  format: html
  limit: 10000

打开主题配置文件next/_config.yml找到Local search,将enable设置为true

效果如下:

手机端site-subtitle显示优化

手机端默认显示副标题,个人觉得不太美观,现修改为:默认不显示副标题,显示导航栏的同时显示副标题。效果如图:

原理:编写JavaScript函数,根据导航栏的display属性来决定是否显示副标题,实现方法如下:

给导航栏添加id并隐藏site-subtitle

themes\next\layout\_partials\header\menu.swig中找到<nav class="site-nav">,为其添加id。大概在第3行,将其修改为:

<nav class="site-nav" id="site-nav">

themes\next\layout\_partials\header\brand.swig找到site-subtitle,为其加上id,大概在第21行,修改为:

    {% if subtitle %}
      {% if theme.seo %}
        <h1 class="site-subtitle" itemprop="description" id="site-subtitle">{{ subtitle }}</h1>
      {% else %}
        <p class="site-subtitle" id="site-subtitle">{{ subtitle }}</p>
      {% endif %}
    {% endif %}

设置手机端默认不显示网站副标题。在themes\next\source\css\_common\components\header\site-meta.styl中添加如下样式:

.site-subtitle{
+mobile() {
    display: none;
  }
}

编写JavaScript函数

</script>
<script type="text/JavaScript">
function showSubtitle()
{
  var siteNav=document.getElementById("site-nav");
  if(siteNav.style.display=="block")
  {
   var subTitle=document.getElementById("site-subtitle");
   subTitle.style.display="none";
  }else
  {
   var subTitle=document.getElementById("site-subtitle");
   subTitle.style.display="block";
  }
}
</script>

将其放到任意一个*.swig文件中,在_layout.swig中引入即可。我的处理方法是,在themes\next\layout\_scripts\文件夹中新建myscript文件夹,专门用于存放自己添加的JavaScript代码。在里面创建一个myscript.swig文件,将上述代码copy到里面,再在themes\next\layout\_layout.swig中添加如下代码引入:

{%  include  '_scripts/myscript/myscript.swig'  %}

点击网站标题旁边的按钮时触发JavaScript函数

themes\next\layout\_partials\header\brand.swig中给<button></button>添加 onclick 事件,最终代码如下:

  <div class="site-nav-toggle">
    <button aria-label="{{ __('accessibility.nav_toggle') }}" onclick="showSubtitle()">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>

博文置顶

打开Hexo 站点node_modules/hexo-generator-index/lib/generator.js文件。代码全部替换为:

'use strict';
var pagination = require('hexo-pagination');
module.exports = function(locals){
  var config = this.config;
  var posts = locals.posts;
    posts.data = posts.data.sort(function(a, b) {
        if(a.top && b.top) { // 两篇文章top都有定义
            if(a.top == b.top) return b.date - a.date; // 若top值一样则按照文章日期降序排
            else return b.top - a.top; // 否则按照top值降序排
        }
        else if(a.top && !b.top) { // 以下是只有一篇文章top有定义,那么将有top的排在前面(这里用异或操作居然不行233)
            return -1;
        }
        else if(!a.top && b.top) {
            return 1;
        }
        else return b.date - a.date; // 都没定义按照文章日期降序排
    });
  var paginationDir = config.pagination_dir || 'page';
  return pagination('', posts, {
    perPage: config.index_generator.per_page,
    layout: ['index', 'archive'],
    format: paginationDir + '/%d/',
    data: {
      __index: true
    }
  });
};

打开文章添加top字段,设置数值,数值越大文章越靠前

---
title: https://www.zdaiot.com/%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/Windows%E4%B8%8B%E4%BD%BF%E7%94%A8hexo%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/
date: 2018-07-29 21:12:14
updated: 2017-7-30 18:18:54 #手动添加更新时间
tags:
copyright: true
top: 100
---

每篇文章末尾统一添加“本文结束”标记

在路径/themes/next/layout/_macro中新建 passage-end-tag.swig 文件,并添加以下内容:

<div>
    {% if not is_index %}
        <div style="text-align:center;color: #ccc;font-size:14px;">------ 本文结束------</div>
    {% endif %}
</div>

打开themes/next/layout/_macro/下的post.swig文件,添加:

<div>
  {% if not is_index %}
  {% include 'passage-end-tag.swig' %}
  {% endif %}
</div>

如图所示,如图所示,注意顺序后影响文中末尾图中项出现的次序:

然后打开themes/next下的_config.yml文件,在末尾添加:

# 文章末尾添加“本文结束”标记
passage_end_tag:
enabled: true

修改访问URL路径

  • 默认情况下访问URL路径为:domain/2017/08/18/关于本站,修改为domain/About/关于本站
  • 编辑Hexo 站点下的_config.yml文件,修改其中的permalink字段
permalink: :category/:title/

给代码块添加复制功能(暂未成功)

  • 下载插件clipboard.js
  • 打开themes/next/source/lib/,新建文件夹clipboard
  • 把下载clipboard.js下的src文件夹下的文件拖动到clipboard文件夹下
  • 打开themes/next/source/js/src/,新建文件custom.js,代码如下:
//此函数用于创建复制按钮
function createCopyBtns() {
    var $codeArea = $("figure table");
    //查看页面是否具有代码区域,没有代码块则不创建 复制按钮
    if ($codeArea.length > 0) {
        //复制成功后将要干的事情
        function changeToSuccess(item) {
             $imgOK = $("#copyBtn").find("#imgSuccess");
                if ($imgOK.css("display") == "none") {
                    $imgOK.css({
                        opacity: 0,
                        display: "block"
                    });
                    $imgOK.animate({
                        opacity: 1
                    }, 1000);
                    setTimeout(function() {
                        $imgOK.animate({
                            opacity: 0
                        }, 2000);
                    }, 2000);
                    setTimeout(function() {
                        $imgOK.css("display", "none");
                    }, 4000);
                };
        };
        //创建 全局复制按钮,仅有一组。包含:复制按钮,复制成功响应按钮
        //值得注意的是:1.按钮默认隐藏,2.位置使用绝对位置 position: absolute; (position: fixed 也可以,需要修改代码)
        $(".post-body").before('<div id="copyBtn" style="opacity: 0; position: absolute;top:0px;display: none;line-height: 1; font-size:1.5em"><span id="imgCopy" ><i class="fa fa-paste fa-fw"></i></span><span id="imgSuccess" style="display: none;"><i class="fa fa-check-circle fa-fw" aria-hidden="true"></i></span>');
        //创建 复制 插件,绑定单机时间到 指定元素,支持JQuery
        var clipboard = new Clipboard('#copyBtn', {
            target: function() {
                //返回需要复制的元素内容
                return document.querySelector("[copyFlag]");
            },
            isSupported: function() {
                //支持复制内容
                return document.querySelector("[copyFlag]");
            }
        });
        //复制成功事件绑定
        clipboard.on('success',
            function(e) {
                //清除内容被选择状态
                e.clearSelection();
                changeToSuccess(e);
            });
        //复制失败绑定事件
        clipboard.on('error',
            function(e) {
                console.error('Action:', e.action);
                console.error('Trigger:', e.trigger);
            });
        //鼠标 在复制按钮上滑动和离开后渐变显示/隐藏效果
        $("#copyBtn").hover(
            function() {
                $(this).stop();
                $(this).css("opacity", 1);
            },
            function() {
                $(this).animate({
                    opacity: 0
                }, 2000);
            }
        );
    }
}
//感应鼠标是否在代码区
$("figure").hover(
    function() {
        //-------鼠标活动在代码块内
        //移除之前含有复制标志代码块的 copyFlag
        $("[copyFlag]").removeAttr("copyFlag");
        //在新的(当前鼠标所在代码区)代码块插入标志:copyFlag
        $(this).find(".code").attr("copyFlag", 1);
        //获取复制按钮
        $copyBtn = $("#copyBtn");
        if ($copyBtn.lenght != 0) {
            //获取到按钮的前提下进行一下操作
            //停止按钮动画效果
            //设置为 显示状态
            //修改 复制按钮 位置到 当前代码块开始部位
            //设置代码块 左侧位置
            $copyBtn.stop();
            $copyBtn.css("opacity", 0.8);
            $copyBtn.css("display", "block");
            $copyBtn.css("top", parseInt($copyBtn.css("top")) + $(this).offset().top - $copyBtn.offset().top + 3);
            $copyBtn.css("left", -$copyBtn.width() - 3);
        }
    },
    function() {
        //-------鼠标离开代码块
        //设置复制按钮可见度 2秒内到 0
        $("#copyBtn").animate({
            opacity: 0
        }, 2000);
    }
);
//页面载入完成后,创建复制按钮
$(document).ready(function() {
  createCopyBtns();
});
  • 打开themes/next/layout/_custom/,新建文件custom.swig,代码如下:
<script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script>
<script type="text/javascript" src="/js/src/custom.js"></script>
  • 修改文件themes/next/layout/_layout.swig,在标签</body>上面插入代码:
{% include '_custom/custom.swig' %}

静态资源压缩

主要是压缩html,css,js等等静态资源,可以适当减少请求的数据量,在站点目录下,执行下面命令:

npm install gulp -g
npm install gulp-minify-css gulp-uglify gulp-htmlmin gulp-htmlclean gulp --save

Hexo 站点下添加gulpfile.js文件,文件内容如下:

var gulp = require('gulp');
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var htmlclean = require('gulp-htmlclean');
// 压缩 public 目录 css
gulp.task('minify-css', function() {
    return gulp.src('./public/**/*.css')
        .pipe(minifycss())
        .pipe(gulp.dest('./public'));
});
// 压缩 public 目录 html
gulp.task('minify-html', function() {
  return gulp.src('./public/**/*.html')
    .pipe(htmlclean())
    .pipe(htmlmin({
         removeComments: true,
         minifyJS: true,
         minifyCSS: true,
         minifyURLs: true,
    }))
    .pipe(gulp.dest('./public'))
});
// 压缩 public/js 目录 js
gulp.task('minify-js', function() {
    return gulp.src('./public/**/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('./public'));
});
// 执行 gulp 命令时执行的任务
gulp.task('default', [
    'minify-html','minify-css','minify-js'
]);

只需要每次在执行generate命令后执行gulp就可以实现对静态资源的压缩,压缩完成后执行deploy命令同步到服务器

hexo g && gulp
hexo d

项目主页添加README

Github上博客的仓库主页空荡荡的,没有README。如果把README.md放入source文件夹,hexo g生成时会被解析成html文件,放到public文件夹,生成时又会自动删除。

解决方法很简单,在source目录下新建文件README.mdown,在里面写README即可。hexo g会把它复制到public文件夹,且不会被解析成html

引入第三方服务

不同于上面的服务的是,这些第三方服务适用于不同的主题

加入畅言评论功能

本站使用的是畅言:http://changyan.kuaizhan.com/
注册设置完毕之后,进入畅言的后台,在后台总览中,可以找到appid,appkey,在Hexo/_config.yml中加入changyan字段:

changyan:
  enable: true
  appid: cyttqOlcY
  appkey: e055f226ee07c801c76f47b3a44323c2

加入百度数据统计与分析功能

本站点使用的是百度统计 http://tongji.baidu.com/ 。加入数据统计与分析功能步骤如下:

注册站长账号并登陆,在这里 http://tongji.baidu.com/web/register 注册站长账号,并填写信息,网站域名和网站首页以下图为例来填写,注册完成后并登陆

在跳转的页面中会显示下图,复制hm.js后的id值

添加baidu_analytics字段,在站点Hexo/theme/next_config.yml中添加baidu_analytics字段,值为上步复制的id值:

baidu_analytics: 0b0b58037319da4959d5a3c014160ccd

至此,该功能已成功加入,大约过20min后在百度统计上可以看到站点的访问情况,如下图:

博客百度站长平台自动链接提交

在百度搜索引擎搜索自己的域名查看是否收录 site:zdaiot.com

百度的 SEO 是个很蛋疼的事情,讲道理的话应该说是比较麻烦的。

有时候百度的爬虫因为各种原因会爬不到我们的网站,所以需要我们主动进行链接提交。

百度提供了三种方法来让我们提交链接:

主动推送

请注意, 本插件的配置文件中包含秘钥, 请您妥善管理好您的博客源码。
您可以把源码保存在本地
如果要托管在git仓库里,请选择私有仓库,博主本人选择的是免费的gitlab

优点:
某些主机,比如Github,禁止百度爬虫访问博客,导致博客无法被百度收录。多亏百度提供了主动提交的接口,这才有了个补救的方法。
除此之外, 使用主动推送还会达到如下功效:

  • 及时发现:可以缩短百度爬虫发现您站点新链接的时间,使新发布的页面可以在第一时间被百度收录
  • 保护原创:对于网站的最新原创内容,使用主动推送功能可以快速通知到百度,使内容可以在转发之前被百度发现

首先注册百度站长工具,登录后,在用户中心->站点管理中添加个人信息,如下所示:

然后,在用户中心->站点管理添加网站

最后一步提示,按照图中的要求进行验证即可这里推荐使用CNAME验证

网站支持->数据引入->链接提交

往下拉,找到准入密匙,显示如下图:

首先,在Hexo根目录下,安装本插件:

npm install hexo-baidu-url-submit --save

然后,同样在根目录下,把以下内容配置到`hexo/_config.yml’文件中:

baidu_url_submit:
  count: 1 ## 提交最新的一个链接
  host: www.zdaiot.com ## 在百度站长平台中注册的域名
  token: your_token ## 请注意这是您的秘钥, 所以请不要把博客源代码发布在公众仓库里!
  path: baidu_urls.txt ## 文本文档的地址, 新链接会保存在此文本文档里

其次,记得查看`hexo/_config.yml’文件中url的值, 必须包含是百度站长平台注册的域名(一般有www),比如:

# URL
## If your site is put in a subdirectory, set url as 'http://yoursite.com/child' and root as '/child/'
url: http://www.zdaiot.com
root: /
permalink: :category/:title/
permalink_defaults:

更改deploy:

# Deployment
## Docs: https://hexo.io/docs/deployment.html
deploy:
- type: git
  repository: [email protected]:zdaiot/zdaiot.github.io.git
  branch: master
- type: baidu_url_submitter

YAML依靠缩进来确定元素间的从属关系。因此,请确保每个deployer的缩进长度相同,并且使用空格缩进。

推送功能的实现,分为两部分:

  • 新链接的产生, hexo generate 会产生一个文本文件,里面包含最新的链接
  • 新链接的提交, hexo deploy 会从上述文件中读取链接,提交至百度搜索引擎

显示如下图所示的字样,即可代表推送成功

自动推送

百度提供了一个 js 脚本,可以在有用户访问页面的时候自动把网址推送给 baidu。

脚本如下:

<pre id="clipboard_textarea"><script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>
</pre>

如果是netxt主题,next主题配置文件next/_config.yml中的baidu_push设置为true,就可以了。而其他的主题,我们只需要把这个脚本嵌入到我们的代码里面就可以了。

例如,笔者使用的是 hexo 的 next 主题,所以我在themes/next/layout里面找了一圈,发现最基本的 template 是_layout.swig,于是我把这段代码加在了这个文件的 body 部分的最后。这样就可以了,非常方便!

sitemap

sitemap 的话,我们直接使用插件,,前一个是传统的 sitemap,后一个是百度的 sitemap(如果你blog托管在GitHub,并且你不想在多花钱弄百度抓取,可以不用安装百度的sitemap)

npm install hexo-generator-sitemap --save
npm install hexo-generator-baidu-sitemap --save

然后在hexo/_config.yml里面配置一下:

sitemap:
  path: sitemap.xml
baidusitemap:
  path: baidusitemap.xml
  • 之后去百度站长平台提交一下 sitemap 的路径就好,一般都是www.example.com/baidusitemap.xml

  • 当仅当您的网站包含不希望被搜索引擎收录的内容时,才需要使用robots.txt文件。如果您希望搜索引擎收录网站上所有内容,请勿建立robots.txt文件或者创建一个内容为空的robots.txt文件。添加蜘蛛协议在hexo/source文件夹下新建robots.txt文件,文件内容如下,Allow字段的值即为允许搜索引擎爬区的内容,/表示网站首页,/categories/为分类页面,如果菜单栏还有其他选项都可以按照格式自行添加。注意这些要跟自己网站目录一一对应:

User-agent: *
Allow: /
Allow: /archives/
Allow: /tags/
Allow: /categories/

Disallow: /vendors/
Disallow: /js/
Disallow: /css/
Disallow: /fonts/
Disallow: /vendors/
Disallow: /fancybox/

Sitemap: http://www.zdaiot.com/sitemap.xml
Sitemap: http://www.zdaiot.com/baidusitemap.xml

注:当网站部署在github上时,robot.txt百度检查更新提示百度暂时无法连接您的服务器,请检查服务器的设置,确保您网站的服务器能被正常访问。错误码:404

添加脚本

上述各种方法,甚至包括什么迁移至gitlab等对我来说不管用,但是下面方法竟然让百度收录了,在此记录一下:

附上推送脚本,其中的url = XXXXXXXXXXXXXXXXXXXXXXXXX,需要打开http://zhanzhang.baidu.com/linksubmit/index 找到自己的推送接口填上去

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: LoveNight
# @Date:   2015-11-16 20:45:59
# @Last Modified by:   LoveNight
# @Last Modified time: 2015-11-19 15:28:50
import os,io
import sys
import json
from bs4 import BeautifulSoup as BS
import requests
import msvcrt

"""
hexo 博客专用,向百度站长平台提交所有网址

本脚本必须放在hexo博客的根目录下执行!需要已安装生成百度站点地图的插件。
百度站长平台提交链接:http://zhanzhang.baidu.com/linksubmit/index 从中找到自己的接口调用地址
主动推送:最为快速的提交方式,推荐您将站点当天新产出链接立即通过此方式推送给百度,以保证新链接可以及时被百度收录。

"""


url = XXXXXXXXXXXXXXXXXXXXXXXXX
baidu_sitemap = os.path.join(sys.path[0], 'public', 'baidusitemap.xml')
google_sitemap = os.path.join(sys.path[0], 'public', 'sitemap.xml')
sitemap = [baidu_sitemap, google_sitemap]

assert (os.path.exists(baidu_sitemap) or os.path.exists(
    google_sitemap)), "没找到任何网站地图,请检查!"


# 从站点地图中读取网址列表
def getUrls():
    urls = []
    for _ in sitemap:
        if os.path.exists(_):
            with io.open(_, "r", encoding="utf-8") as f:
                xml = f.read()
            soup = BS(xml, "html.parser")
            tags = soup.find_all("loc")
            urls += [x.string for x in tags]
            if _ == baidu_sitemap:
                tags = soup.find_all("breadCrumb", url=True)
                urls += [x["url"] for x in tags]
    return urls


# POST提交网址列表
def postUrls(urls):
    urls = set(urls)  # 先去重
    print("一共提取出 %s 个网址" % len(urls))
    data = "\n".join(urls)
    return requests.post(url, data=data).text


if __name__ == '__main__':

    urls = getUrls()
    result = postUrls(urls)
    print("提交结果:")
    print(result)
    msvcrt.getch()

刚发现个问题,如果在百度站长平台使用「 文件验证 」,hexo d之前要手动把验证文件放到public目录下。

如果贪方便放在source文件夹下,执行hexo g 时会往里塞新内容导致验证失败。

将个人域名与 GitHub Pages 的空间绑定

  • 点击对应域名的"解析"

  • 点击添加解析,记录类型选A或CNAME,A记录的记录值就是ip地址,github(官方文档)提供了两个IP地址,192.30.252.153和192.30.252.154,这两个IP地址为github的服务器地址,两个都要填上,解析记录设置两个www和@,线路就默认就行了,CNAME记录值填你的github博客网址。如我的是zdaiot.github.io

这些全部设置完成后,此时你并不能要申请的域名访问你的博客。接着你需要做的是在hexo根目录的source文件夹里创建CNAME文件,不带任何后缀,里面添加你的域名信息,如:www.zdaiot.com

搭建完成访问出现404 可能的原因是:

  1. 绑定了个人域名,但是域名解析错误。
  2. 域名解析正确但你的域名是通过国内注册商注册的,你的域名因没有实名制而无法访问。
  3. 你认为配置没有问题,那么可能只是你的浏览器在捣鬼,可尝试清除浏览器缓存再访问或者换个浏览器访问。
  4. 也有可能是你的路由器缓存导致的错觉,所以也可以尝试换个局域网访问你的网站。
  5. 最有可能的原因是你下载的hexo有问题,导致所有的东西都上传到了github,而导致index页面在主域名的下一级目录。你可以尝试查看上传的内容,找到index页面,在域名后面添加下一级目录。若能访问index页面(此时样式可能是乱的),则证明是hexo安装有问题,笔者当时遇到的就是这个问题。可卸载重新安装。

注:1,2默认你的CNAME文件配置没有问题,如果没有绑定个人域名,则不需要CNAME文件。

发表博文

辛苦了这么久,终于回到我们搭建博客最初的目标–写作,现在来看看怎么写博文并发表吧(__)。

新建页面

上面新建的博文是显示在单个文章界面,这里新建的页面是作为单个页面显示的,比如下图的分类、标签、归档和关于我,你点击后都是显示为单个页面。

你只需要记住新建博文是用上面的方法,新建页面是用这里的方法就行了,这里也采用命令新建页面:

hexo new page "页面名称"

命令执行完后,就会发现在在

Hexo\source

目录中多了一个文件夹,里面还有一个index.md,这就代表我们新建了一个页面。

新建博文

我们可以使用命令新建一篇博文,使用 Git Shell 进入 Hexo 文件夹,输入以下命令:

hexo new "文章题目"

命令执行完后,就会发现在

Hexo\source_posts

目录中多了一个文件博文名.md,这就是我们刚才新建的博文。

此外,我们也可以直接进入

Hexo\source_posts

目录中,右键新建一个文本文档,将名字改为博文名.md,这样也新建了一篇博文。

写博文

用文本编辑器打开上面新建的博文,如下图所示:

新建的页面略有不同,没有tags和categories标签。
三个”-“后面就是博文的正文内容,接下来就是正儿八经地撰写博文了。

发博文

呼啦啦,博文写好了,你得发表出去别人才看得到呀。依然在 Git Shell 中进入 Hexo 文件夹,执行下面几条命令,将博客部署到 GitHub 上:

hexo clean
hexo generate
(若要本地预览就先执行 hexo server)
hexo deploy

快捷命令:

hexo g == hexo generate
hexo d == hexo deploy
hexo s == hexo server
hexo n == hexo new

还能组合使用,如:

hexo d -g

刷新你的个人博客,就可以看到新鲜出炉的博文了,赶紧邀请小伙伴们来欣赏吧。

插入优酷视频

新建一个markdown文件

hexo new "video"

加入下面几行代码:

我怕我只是你生命中的一盏灯,掩盖了上一人,照亮了下一人,一盏灯,幸福而愚蠢!:
<iframe 
    height=498 width=510 
    src="http://player.youku.com/embed/XMjg3ODQzMjQ="
    frameborder=0 allowfullscreen>
</iframe>

其中,src的来源如下,在通用代码里面找到网址,填到上方:

hexo多平台同步

我基于这个回答来解决这个问题的。问题主要出在theme上,由于NexT主题引自第三方,所以这就牵扯到git中的submodule问题了。想偷懒把不引入,但是好像不行,于是按以下思路进行解决:fork NexT官方的github到自己的仓库,然后引入子模块,我这边不知道为什么有“already exists in the index”的问题,执行如下命令:

git rm -r --cached themes/next

由于我是已经配置好了自己的NexT,为了不让它遗失,我先把它剪贴出来,再添加submodlue:

git init
git submodule add [email protected]:zdaiot/hexo-theme-next.git themes/next

然后再把自己的配置覆盖fork下来的NexT仓库。
我们先要push submodule,在theme/next目录下依次执行:

cd themes/next
git add .
git commit -m "next settings in fork next rep"
git push origin master //这是提交到fork后主题的仓库

origin就是一个名字,它是在你clone一个托管在Github上代码库时,git为你默认创建的指向这个远程代码库的标签

注意有的时候主题下并不是所有文件夹都用同步,打开themes\next\.gitignore文件,里面有忽略的文件夹与文件

这样,是提交到zdaiot/hexo-theme-next仓库。然后我们再更新zdaiot.github.io仓库:

cd ../../ //切到仓库的根目录
git add .
git commit -m "update next settings in blog sources branch"
git remote add origin [email protected]:zdaiot/zdaiot.github.io.git //将本地与Github项目对接
git push origin --delete hexo //删除hexo分支
git branch hexo   //新建分支
git checkout hexo //切换分支
git push origin hexo //注意hexo分支

以后写文章,只需要在根目录下(hexo分支)进行git add,commit,push(hexo)操作,例如:

git add .
git commit -m "new post hexo theme sync solution"
git push origin hexo

然后再更新master分支,即对外显示的html部分:

//hexo s -g
hexo d -g  // g为generate 生成,s为本地预览,d为deploy 部署到远程分支

接下来为比较完整的在另一台电脑上的操作过程:

git clone --recursive [email protected]:zdaiot/zdaiot.github.io.git //clone 主仓库
cd zdaiot.github.io/
git checkout hexo //切换到hexo,以后基本都是基于此分支,master分支用hexo -d
cd themes/next/
git submodule init
git submodule update //获取我的NexT主题的配置
//接下来的任务主要是配置环境,nodejs安装,hexo等等。以下安装可能不全面
//先切换到仓库根目录
npm install -g hexo
npm install hexo-cli -g
npm install hexo --save
npm install hexo-server --save
npm install hexo-deployer-git --save
npm install

WordPress迁移

首先,安装 hexo-migrator-wordpress 插件。

npm install hexo-migrator-wordpress --save

在 WordPress 仪表盘中导出数据(“Tools” → “Export” → “WordPress”)(详情参考WP支持页面)。

插件安装完成后,执行下列命令来迁移所有文章。source 可以是 WordPress 导出的文件路径或网址

将导出的xml文件放到Hexo根目录

hexo migrate wordpress

可能出现的错误

问题一

[git]warning: LF will be replaced by CRLF | fatal: CRLF would be replaced by LF
遇到这两个错误,是因为Git的换行符检查功能。

core.safecrlf

Git提供了一个换行符检查功能(core.safecrlf),可以在提交时检查文件是否混用了不同风格的换行符。这个功能的选项如下:

  • false - 不做任何检查
  • warn - 在提交时检查并警告
  • true - 在提交时检查,如果发现混用则拒绝提交

建议使用最严格的 true 选项。

core.autocrlf

假如你正在Windows上写程序,又或者你正在和其他人合作,他们在Windows上编程,而你却在其他系统上,在这些情况下,你可能会遇到行尾结束符问题。这是因为Windows使用回车和换行两个字符来结束一行,而Mac和Linux只使用换行一个字符。虽然这是小问题,但它会极大地扰乱跨平台协作。

Git可以在你提交时自动地把行结束符CRLF转换成LF,而在签出代码时把LF转换成CRLF。用core.autocrlf来打开此项功能,如果是在Windows系统上,把它设置成true,这样当签出代码时,LF会被转换成CRLF:

$ git config --global core.autocrlf true

Linux或Mac系统使用LF作为行结束符,因此你不想 Git 在签出文件时进行自动的转换;当一个以CRLF为行结束符的文件不小心被引入时你肯定想进行修正,把core.autocrlf设置成input来告诉 Git 在提交时把CRLF转换成LF,签出时不转换:

$ git config --global core.autocrlf input

这样会在Windows系统上的签出文件中保留CRLF,会在Mac和Linux系统上,包括仓库中保留LF。

如果你是Windows程序员,且正在开发仅运行在Windows上的项目,可以设置false取消此功能,把回车符记录在库中:

$ git config --global core.autocrlf false

问题二

hexo指令出现YAMLException: duplicated mapping key at line 111, column 1:

  • 查看是否缩进正常,空格或者tab一致
  • YAML依靠缩进来确定元素间的从属关系。因此,请确保每个deployer的缩进长度相同,并且使用空格缩进。

错误三

若把整个hexo根目录给提交了上去,这不是我要的结果啊,说好的只提交public文件夹的呢!查看hexo根目录,存在“.git”这个目录,原来是在hexo根目录下,我进行过git init的操作,删除“.git”文件夹即可。

其他问题

spawn git ENOENT

解决方法在这里:spawn git ENOENT解决方法
头像图片无法显示:hexo头像无法显示【解决办法】

调试

打开网站,开启F12,查看console,报的错,对应去修改

如下图所示,可以去调试移动端的布局

参考资料

用 GitHub + Hexo 建立你的第一个博客
hexo的next主题个性化教程:打造炫酷网站
Hexo NexT主题内接入网页在线联系功能
hexo的next主题打赏
Hexo发布博客引用自带图片的方法
Next主页
hexo中完美插入本地图片
hexo next 主题配置 gitalk 评论后无法初始化创建 issue
报错出现 Error: Validation Failed. #102
在Hexo发布博客的MarkDown文件中引入JS代码
Gitment评论功能接入踩坑教程
Hexo的Next主题详细配置
Hexo-Next-主题优化(一)
Hexo+Next个人博客主题优化
Hexo部署至多个repo上,多域名指向
Hexo插件之百度主动提交链接
hexo 博客百度站长平台自动链接提交
Hexo+nexT主题搭建个人博客
如何解决github+Hexo的博客多终端同步问题
基于Hexo的博客同步中的一些问题
Hexo NexT主题中添加百度分享功能
next主题进阶教程
Hexo+nexT主题搭建个人博客
脚本推送百度


One more thing

更多关于人工智能、Python、C++、计算机等知识,欢迎访问我的个人博客进行交流, 点这里~~

猜你喜欢

转载自blog.csdn.net/zdaiot/article/details/82833901
今日推荐