博客从 typecho 迁移到 Hexo

Hexo 环境搭建

使用 codinggithub.io 的 pages 服务,绑定了自己的域名,做了双线解析,国内用户解析到 coding ,国外用户解析到 github.io,访问速度很满意(本来就是静态文件,访问速度很快)。
Hexo 环境的搭建,这里不再赘述,主要介绍如何导出 typecho 的数据和 Hexo 站点的配置以及 Next 主题的配置及优化。

typecho 数据导出

文章数据的导出

花了点时间把 typecho 的文章全部改写成 Markdown 的格式,方便我导出为 md 文件,使用了 github 上面一个开源的 python 项目 Typecho2Hexo 进行 typecho 文章数据的导出。稍微修改后如下所示:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# -*- coding: utf-8 -*-

import codecs
import os
import torndb
import arrow

def create_data(db):
    # 创建分类和标签
    categories = db.query("select type, slug, name from typecho_metas")
    for cate in categories:
        path = 'data/%s' % cate.slug
        if not os.path.exists(path):
            os.makedirs(path)
        f = codecs.open('%s/index.md' % path, 'w', "utf-8")
        f.write("title: %s\n" % cate.slug)
        f.write("date: %s\n" % arrow.now().format('YYYY-MM-DD HH:mm:ss'))
        # 区分分类和标签
        if cate.type == 'category':
            f.write('type: "categories"\n')
        elif cate.type == 'tags':
            f.write('type: "tags"\n')
        # 禁止评论
        f.write("comments: true\n")
        f.write("---\n")
        f.close()

    # 创建文章
    entries = db.query("select cid, title, slug, text, created from typecho_contents where type='post'")
    for e in entries:
        title = e.title
        urlname = e.slug
        print(title)
        content = str(e.text).replace('<!--markdown-->', '')
        tags = []
        category = ""
        # 找出文章的tag及category
        metas = db.query(
            "select type, name, slug from `typecho_relationships` ts, typecho_metas tm where tm.mid = ts.mid and ts.cid = %s",
            e.cid)
        for m in metas:
            if m.type == 'tag':
                tags.append(m.name)
            if m.type == 'category':
                category = m.slug
        path = 'data/_posts/'
        if not os.path.exists(path):
            os.makedirs(path)
        f = codecs.open(r"%s%s.md" % (path,title), 'w', "utf-8")
        f.write("---\n")
        f.write("title: %s\n" % title)
        f.write("date: %s\n" % arrow.get(e.created).format('YYYY-MM-DD HH:mm:ss'))
        f.write("categories: %s\n" % category)
        f.write("tags: [%s]\n" % ','.join(tags))
        f.write("urlname: %s\n" % urlname)
        f.write("---\n")
        f.write(content)
        f.close()


def main():
    # 把数据库连接信息
    db = torndb.Connection(host="******", database="******", user="******", password="******")
    create_data(db)

if __name__ == "__main__":
    main()

评论数据的导出

直接导出 typecho_comment 为 csv 模式,手动处理成 LeanCloud(valine评论插件使用leancloud)的数据格式,因为评论较少,故直接手动处理。

Hexo配置

1. 固定链接配置

编辑站点 _config.yml 文件修改以下内容,是文章的 URL 链接为 域名/分类/文章名的格式.html,urlname由文章中传入

1
2
3
4
5
6
7
# URL
## If your site is put in a subdirectory, set url as 'http://yoursite.com/child' and root as '/child/'
url: https://www.sunmite.com/
root: /
permalink: :category/:urlname.html
permalink_defaults:
  urlname: index

2. RSS配置

  • 安装插件
1
npm install hexo-generator-feed --save
  • 在站点 _config.yml 文件中增加以下内容
1
2
3
4
5
6
plugins: hexo-generator-feed 

feed:
  type: atom ##feed类型 atom或者rss2
  path: atom.xml ##feed路径
  limit: 20  ##feed文章最小数量

3. sitemap配置

  • 安装插件
1
npm install hexo-generator-sitemap --save
  • 在站点 _config.yml 文件中增加以下内容
1
2
sitemap:
  path: sitemap.xml 

Next配置及优化

主题配置

1. 页脚设置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
footer:
  # Specify the date when the site was setup.
  # If not defined, current year will be used.
  since: 2014 #建站时间

  # Icon between year and copyright info.
  icon: heart #修改默认图标为♥

  # If not defined, will be used `author` from Hexo main config.
  copyright:
  # -------------------------------------------------------------
  # Hexo link (Powered by Hexo).
  powered: true

  theme:
    # Theme & scheme info link (Theme - NexT.scheme).
    enable: true
    # Version info of NexT after scheme info (vX.X.X).
    version: false # 不显示主题版本

2. 首页菜单设置

1
2
3
4
5
6
7
8
9
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

3. 主题样式

1
2
3
4
5
# Schemes
#scheme: Muse
scheme: Mist    #本站选用
#scheme: Pisces
#scheme: Gemini

4. 个人社交账号

1
2
3
4
5
6
7
social:
  GitHub: https://github.com/tanmx || github
  E-Mail: mailto:tanmingxiao@gmail.com || envelope
  #Google: https://plus.google.com/yourname || google
  Twitter: https://twitter.com/lianyu_ || twitter
  微博: https://weibo.com/lovelongerlonger || weibo
  知乎: https://www.zhihu.com/people/tan-ming-xiao || gratipay  #由于FontAwesome暂未收录知乎的图标,这里使用其他图标代替

5. 友情链接

1
2
3
4
5
6
7
8
links_icon: link
links_title: 延伸阅读
#links_layout: block
links_layout: inline
links:
  陈沙克日志: http://www.chenshake.com/
  OpenStack Docs: https://docs.openstack.org/
  孔令贤的个人博客: https://lingxiankong.github.io/index.html

6. 目录设置

1
2
3
4
5
6
7
8
toc:
  enable: true

  # Automatically add list number to toc.
  number: false  #关闭目录自动添加序号

  # If true, all words will placed on next lines if header width longer then sidebar width.
  wrap: false

7. Valine留言系统配置

详细用法可以参考 Valine官方文档

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Valine.
# You can get your appid and appkey from https://leancloud.cn
# more info please open https://valine.js.org
valine:
  enable: true
  appid:  # your leancloud application appid
  appkey:  # your leancloud application appkey
  notify: true # mail notifier , https://github.com/xCss/Valine/wiki
  verify: false # Verification code
  placeholder: (发表评论) # comment box placeholder
  avatar: mm # gravatar style
  guest_info: nick,mail,link # custom comment header
  pageSize: 10 # pagination size

8. Google、Bing 站长验证

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Google Webmaster tools verification setting
# See: https://www.google.com/webmasters/
google_site_verification: ******   #获取自己站长验证代码

# Google Analytics
#google_analytics:

# Bing Webmaster tools verification setting
# See: https://www.bing.com/webmaster/
bing_site_verification: ******  #获取自己站长验证代码

9. 显示每篇文章的访问量

1
2
3
4
5
6
# Show number of visitors to each article.
# You can visit https://leancloud.cn get AppID and AppKey.
leancloud_visitors:
  enable: true
  app_id: #<app_id>
  app_key: #<app_key>

10. 百度推送

1
2
# Enable baidu push so that the blog will push the url to baidu automatically which is very helpful for SEO
baidu_push: true

11. 开启本地搜索

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Local search
# Dependencies: https://github.com/theme-next/hexo-generator-searchdb
local_search:
  enable: true
  # if auto, trigger search by changing input
  # if manual, trigger search by pressing enter key or search button
  trigger: auto
  # show top n results per article, show all results by setting to -1
  top_n_per_article: 1
  # unescape html strings to the readable one
  unescape: false

12. 启用加载进度条

1
2
3
# Progress bar in the top during page loading.
# Dependencies: https://github.com/theme-next/theme-next-pace
pace: true

13. 设置作者头像圆角,旋转

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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 
  # If true, the avatar would be dispalyed in circle. 
  rounded: true  #开启圆角头像
  # The value of opacity should be choose from 0 to 1 to set the opacity of the avatar.
  opacity: 1
  # If true, the avatar would be rotated with the cursor.
  rotated: true  #旋转

14. 修改文章底部上一篇和下一篇的顺序

进入一篇文章,在文章底部,有上下篇的链接(< >),但是点 > 发现进入的是页面中的的上面那篇文章,与操作习惯不符,修改配置使之符合一般习惯。

1
2
3
# Show previous post and next post in post footer if exists
# Available values: left | right | false
post_navigation: right

主题优化

1. 设置博文内链接为蓝色

修改 /themes/next/source/css/_common/components/post/post.styl 这文件末尾添加如下内容

1
2
3
4
5
6
7
8
9
 /* 链接蓝色 */
.post-body p a{
     color: #0593d3;
     border-bottom: none;
     &:hover {
       color: #0477ab;
       text-decoration: underline;
     }
   }

2. 增加底部版权信息(NexT新版已经支持此feather,主题配置文件开启 custom_text 即可)

增加 Coding 的版权信息,不然访问网站的时候会有 Coding 的跳转页面 编辑 /themes/next/layout/_partials/footer.swig 修改一下部分

1
2
3
4
{ #
coding版权信息
# }
| Hosted by <a href="https://pages.coding.me" >Coding Pages</a>

3. 修改文章底部的那个带#号的标签(NexT新版已经支持此feather,主题配置文件开启 tag_icon: true 即可)

修改模板/themes/next/layout/_macro/post.swig,搜索 rel=“tag”>#

1
2
将 # 换成 
<i class="fa fa-tag"></i>

4. 修改头像为圆形(NexT新版已经支持此feather,开启方法在 主题配置13中)

编辑 /themes/next/source/css/_common/components/sidebar/sidebar-author.styl,在 site-author-image 里面添加如下代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
.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;

5. 修改文章底部上一篇和下一篇的顺序(NexT新版已经支持,开启方法在 主题配置14中)

进入一篇文章,在文章底部,有上下篇的链接(< >),但是点 > 发现进入的是页面中的的上面那篇文章,与操作习惯不符. 修改 /themes/next/layout/_macro/post.swig 使之符合一般习惯

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{% if not is_index and (post.prev or post.next) %}
  <div class="post-nav">
    <div class="post-nav-next post-nav-item">
-      {% if post.next %}
+      {% if post.prev %}
-        <a href="{{ url_for(post.next.path) }}" rel="next" title="{{ post.next.title }}">
+        <a href="{{ url_for(post.prev.path) }}" rel="prev" title="{{ post.prev.title }}">
-          <i class="fa fa-chevron-left"></i> {{ post.next.title }}
+          <i class="fa fa-chevron-left"></i> {{ post.prev.title }}
        </a>
      {% endif %}
    </div>
    <span class="post-nav-divider"></span>
    <div class="post-nav-prev post-nav-item">
-      {% if post.prev %}
+      {% if post.next %}
-        <a href="{{ url_for(post.prev.path) }}" rel="prev" title="{{ post.prev.title }}">
+        <a href="{{ url_for(post.next.path) }}" rel="next" title="{{ post.next.title }}">
-          {{ post.prev.title }} <i class="fa fa-chevron-right"></i>
+          {{ post.next.title }} <i class="fa fa-chevron-right"></i>
        </a>
      {% endif %}
    </div>
  </div>
{% endif %}

6. 本地加载 Valine.min.js 文件

1
- <div class="power txt-right">Powered By <a href="https://valine.js.org" target="_blank">Valine</a><br>v1.1.9-beta4</div></div>
  • 编辑 /themes/next/layout/_third-party/comments/valine.swig 改用本地 js 文件中增加以下内容
1
2
3
4
5
{% if theme.valine.enable and theme.valine.appid and theme.valine.appkey %}
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
-  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
+  <script src="/js/src/Valine.min.js"></script>
{% if theme.vendors.valine %}

7. 增加本文结束标志

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

1
2
3
4
5
<div>
    {% if not is_index %}
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢阅读-------------</div>
    {% endif %}
</div>

然后编辑 /themes/next/layout/_macro/post.swig文件,在post-body 之后, post-footer 之前添加如下代码(post-footer之前三个DIV)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    {#####################}
    {### END POST BODY ###}
    {#####################}

+	<div>
+        {% if not is_index %}
+        {% include 'passage-end-tag.swig' %}
+        {% endif %}
+     </div>
	
    {% if theme.wechat_subscriber.enabled and not is_index %}
      <div>
        {% include 'wechat-subscriber.swig' %}
      </div>
    {% endif %}
	
    {% if (theme.alipay or theme.wechatpay or theme.bitcoin) and not is_index %}
      <div>
        {% include 'reward.swig' %}
      </div>
    {% endif %}

    {% if theme.post_copyright.enable and not is_index %}
      <div>
        {% include 'post-copyright.swig' with { post: post } %}
      </div>
    {% endif %}

    <footer class="post-footer">
      {% if post.tags and post.tags.length and not is_index %}
        <div class="post-tags">
          {% for tag in post.tags %}
            <a href="{{ url_for(tag.path) }}" rel="tag"><i class="fa fa-tag"></i> {{ tag.name }}</a>
          {% endfor %}
        </div>
      {% endif %}

然后打开主题配置文件 _config.yml ,在末尾添加

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

8. 开启版权信息,并增加版权信息内容

  • 开启版权信息(主题配置文件此项有所修改) 编辑主题配置文件 _config.yml 修改以下配置
1
2
3
post_copyright:
  enable: true
  license: <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a>
  • 增加版权内容:本文标题
  1. 编辑 /themes/next/layout/_partials/post/post-copyright.swig 文件,加入以下内容
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  <li class="post-copyright-author">
    <strong>{{ __('post.copyright.author') + __('symbol.colon') }} </strong>{#
  #}{{ post.author | default(author) }}{#
#}</li>
+  <li class="post-copyright-title">
+    <strong>{{ __('post.copyright.title') + __('symbol.colon') }} </strong>{#
+  #}{{ post.title | default(title) }}{#
+ #}</li>
  <li class="post-copyright-link">
    <strong>{{ __('post.copyright.link') + __('symbol.colon') }}</strong>
    <a href="{{ post.url | default(post.permalink) }}" title="{{ post.title }}">{{ post.url | default(post.permalink) }}</a>
  </li>
  1. 编辑 /themes/next/languages/zh-CN.yml 文件,加入以下内容
1
2
3
4
5
6
  copyright:
    author: 本文作者
+    title: 本文标题
    link: 本文链接
    license_title: 版权声明
    license_content: "本博客所有文章除特别声明外,均采用 %s 许可协议。转载请注明出处!"

9. 使用 valine-admin 添加评论邮件提醒

使用 valine 当有新评论的时候是没有邮件提醒,使用 valine-admin 扩展他的功能。配置方法参考 Hexo 优化 — Valine 扩展之邮件通知,Valine.min.js 使用 Valine-Ex

10. 文章简单加密

安装插件

1
npm install hexo-blog-encrypt

在 hexo 配置文件中启用插件

1
2
3
# 文章加密
encrypt:
  enable: true

文章添加相关字段(后两项可以不填)

1
2
3
password: 文章的密码
message: 输入密码界面提示说明
abstract: 文章界面介绍
一个默默无闻的工程师的日常
Built with Hugo
主题 StackJimmy 设计