概要:

Hexo是一个快速、简洁且高效的静态博客框架,Hexo使用 Markdown(或其它渲染引擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。可以将本地的网页发布到Github page(国外访问速度快)或Coding page(国内访问速度快)上,这样就能通过互联网访问博客网站了,而且是免费的。也可以再购买一个独立域名,绑定解析到Github page空间地址和Coding page空间地址后,就可以用你的特色域名访问博客系统了。

参考资料

搭建Hexo环境

安装 npm

NPM的全称是Node Package Manager ,是一个NodeJS包管理和分发工具,已经成为了非官方的发布Node模块(包)的标准

推荐官网下载。

安装完node后建议设置npm淘宝镜像以加速后面的过程(或使用科学上网工具)。

1
2
npm config set registry https://registry.npm.taobao.org --global
npm config set disturl https://npm.taobao.org/dist --global

安装 hexo

1
sudo npm install -g hexo-cli

配置环境

1
2
3
4
hexo init
npm install
hexo g
hexo s

此时打开: http://localhost:4000 即可看到效果。

hexo 常用的命令

  • $ hexo g 完整命令为 hexo generate,用于生成静态文件。
  • $ hexo s 完整命令为 hexo server,用于启动服务器,主要用来本地预览。
  • $ hexo d 完整命令为 hexo deploy,用于将本地文件发布到github上。
  • $ hexo n 完整命令为 hexo new,用于新建一篇文章。

部署Github仓库

新建部署仓库

  • 新建仓库 命名为: 用户名.github.io

  • 博客工程根目录编辑, _config.yml

    1
    2
    3
    4
    deploy:
    type: git
    repository: git@github.com:bambooxking/bambooxking.github.io.git
    branch: master
  • 执行命令

    1
    2
    hexo generate
    hexo deploy
  • 若执行命令hexo deploy报错:ERROR Deployer not found: git,则执行如下命令来安装hexo-deployer-git

    1
    npm install hexo-deployer-git --save

    再次执行上步命令。

博客部署的迁移

  • 将当前本地的部署提交到 github 仓库。
  • 在要迁移的机器上,将仓库 clone 到本地。
  • 新电脑上, 同样先安装npmhexo, 再将上述分支clone到本地, 执行 npm install 即可快速完成部署。

博客主题配置

可以到Hexo官网主题页去搜寻自己喜欢的theme,这里列一些自己觉得还不错的主题:

hexo-theme-butterfly

Butterfly 安裝文檔(一) 快速開始

Butterfly 安裝文檔(二) 主題頁面

Butterfly 安裝文檔(三) 主題配置-1

Butterfly 安裝文檔(四) 主題配置-2

Butterfly 安裝文檔(六) 進階教程

主题获取

1
git clone -b master https://github.com/bambooxking127/hexo-theme-butterfly.git themes/butterfly

主题生效

博客工程根目录下,修改 _config.yml

1
theme: butterfly

必要的插件安装

1
npm install hexo-renderer-pug hexo-renderer-stylus --save

自定义配置

配置网站图标

修改主题配置文件 butterfly.yml

1
favicon: /img/favicon.png
配置个人头像

修改主题配置文件 butterfly.yml

1
2
3
avatar:
img: /img/avatar.png
effect: true # 头像特效: 一直转圈
配置页面顶部图

修改主题配置文件 butterfly.yml

1
2
3
4
5
6
7
8
# 主页
index_img: https://i.loli.net/2020/05/01/IuWi8QbHvzjlOPw.jpg
# 归档
archive_img:
# 标签页
tag_img:
# 分类也
category_img:
配置文章顶部图

文章配置 front-mattertop_img

音乐页面

安装插件 hexo-tag-aplayer

1
npm install --save hexo-tag-aplayer

新建音乐页面

1
hexo new page music

在 Hexo 根目录 _config.yml 里配置 asset_injectfalse

1
2
aplayer:
asset_inject: false

在你需要使用 aplayer 的页面 Front-matter 添加

1
aplayer: true

使用方法

  • title : 曲目标题
  • author: 曲目作者
  • url: 音乐文件 URL 地址
  • picture_url: (可选) 音乐对应的图片地址
  • narrow: (可选)播放器袖珍风格
  • autoplay: (可选) 自动播放,移动端浏览器暂时不支持此功能
  • width:xxx: (可选) 播放器宽度 (默认: 100%)
  • lrc:xxx: (可选)歌词文件 URL 地址

https://music.163.com/playlist?id=523845661&userid=46562117 ,这个歌单的id就是523845661,公司名可以是tencent、netease或是其他公司

1
2
3
4
5
# 模板
{% aplayer title author url [picture_url, narrow, autoplay, width:xxx, lrc:xxx] %}

# 示例
{% meting "523845661" "netease" "playlist" "theme:#FF4081" "mode:circulation" "mutex:true" "listmaxheight:340px" "preload:auto" %}
电影页面 & 阅读页面

安装插件 hexo-douban

1
npm install hexo-douban --save

配置页面

  • user: 你的豆瓣ID.打开豆瓣,登入账户,然后在右上角点击 “个人主页” ,这时候地址栏的URL大概是这样:”https://www.douban.com/people/xxxxxx/" ,其中的”xxxxxx”就是你的个人ID了。
  • builtin: 是否将生成页面的功能嵌入hexo shexo g中,默认是false,另一可选项为true(1.x.x版本新增配置项)。
  • title: 该页面的标题.
  • quote: 写在页面开头的一段话,支持html语法.
  • timeout: 爬取数据的超时时间,默认是 10000ms ,如果在使用时发现报了超时的错(ETIMEOUT)可以把这个数据设置的大一点。

在 Hexo 根目录 _config.yml 里插入

1
2
3
4
5
6
7
8
9
10
11
12
13
douban:
user: mythsman
builtin: false
book:
title: 'This is my book title'
quote: 'This is my book quote'
movie:
title: 'This is my movie title'
quote: 'This is my movie quote'
game:
title: 'This is my game title'
quote: 'This is my game quote'
timeout: 10000

启动

1
2
# -bgm代表的是book、game、movie三个参数
hexo clean && hexo douban -bm && hexo g && hexo s

升级插件

1
npm install hexo-douban --update --save

需要注意的是,通常大家都喜欢用hexo d来作为hexo deploy命令的简化,但是当安装了hexo douban之后,就不能用hexo d了,因为hexo doubanhexo deploy的前缀都是hexo d

图库页面

新建图库页面

1
hexo new page gallery

修改主题配置文件 butterfly.ymlmenu

1
\- 照片 || /gallery/ || fas fa-images

图库写法

name:图库名字
description:图库描述
link:链接到对应相冊的地址
img-url:图库封面的地址

1
2
3
4
5
<div class="gallery-group-main">
{% galleryGroup name description link img-url %}
{% galleryGroup name description link img-url %}
{% galleryGroup name description link img-url %}
</div>
1
2
3
4
5
<div class="gallery-group-main">
{% galleryGroup '壁紙' '收藏的一些壁紙' '/Gallery/wallpaper' https://i.loli.net/2019/11/10/T7Mu8Aod3egmC4Q.png %}
{% galleryGroup '漫威' '關於漫威的圖片' '/Gallery/marvel' https://i.loli.net/2019/12/25/8t97aVlp4hgyBGu.jpg %}
{% galleryGroup 'OH MY GIRL' '關於OH MY GIRL的圖片' '/Gallery/ohmygirl' https://i.loli.net/2019/12/25/hOqbQ3BIwa6KWpo.jpg %}
</div>

相册写法

1
2
3
{% gallery %}
markdown 圖片格式
{% endgallery %}
1
2
3
4
5
6
7
8
9
10
{% gallery %}
![](https://i.loli.net/2019/12/25/Fze9jchtnyJXMHN.jpg)
![](https://i.loli.net/2019/12/25/ryLVePaqkYm4TEK.jpg)
![](https://i.loli.net/2019/12/25/gEy5Zc1Ai6VuO4N.jpg)
![](https://i.loli.net/2019/12/25/d6QHbytlSYO4FBG.jpg)
![](https://i.loli.net/2019/12/25/6nepIJ1xTgufatZ.jpg)
![](https://i.loli.net/2019/12/25/E7Jvr4eIPwUNmzq.jpg)
![](https://i.loli.net/2019/12/25/mh19anwBSWIkGlH.jpg)
![](https://i.loli.net/2019/12/25/2tu9JC8ewpBFagv.jpg)
{% endgallery %}
文章置顶

安装插件 hexo-generator-indexed

1
npm install hexo-generator-indexed

在 Hexo 根目录 _config.yml 里配置 index_generator

1
2
3
4
5
index_generator:
path: ''
per_page: 10
order_by: -date
pagination_dir: page

在文章的 Front-matter 中增加一个 sticky 参数用来置顶,其值应为大于0的整数,表示置顶的优先级(未指定则默认为 0)。数字越大,文章越靠前。

1
2
3
4
---
title: example
sticky: 100
---
文章隐藏

安装插件 hexo-generator-indexed

1
npm install hexo-generator-indexed

在文章的 Front-matter 中增加一个 hide 参数用来隐藏。

1
2
3
4
---
title: example
hide: true
---
隐藏特定分类中的文章

在 Hexo 根目录 _config.yml 里配置 hide_categories

1
2
3
hide_categories:
- categorie1
- categorie2
文章目录显示

在 Hexo 根目录 _config.yml 里配置 toc

1
2
3
4
toc:
enable: true # 是否显示 TOC
number: true # 是否显示章节数
auto_open: true # auto open the sidebar
文章meta显示

配置文章描述的详细信息

1
2
3
4
5
6
7
8
9
post_meta:
page:
date_type: both # created or updated or both 主頁文章日期是創建日或者更新日或都顯示
categories: true # true or false 主頁是否顯示分類
tags: true # true or false 主頁是否顯示標籤
post:
date_type: both # created or updated or both 文章頁日期是創建日或者更新日或都顯示
categories: true # true or false 文章頁是否顯示分類
tags: true # true or false 文章頁是否顯示標籤
文章版权
1
2
3
4
5
post_copyright:
enable: true
decode: false
license: CC BY-NC-SA 4.0
license_url: https://creativecommons.org/licenses/by-nc-sa/4.0/

如果有文章(例如:转载文章)不需要显示版权,可以在文章 Front-matter 单独设置

1
copyright: false
文章打赏
1
2
3
4
5
6
7
8
9
reward:
enable: true
QR_code:
- img: /img/wechatpay.png
link:
text: wechat
- img: /img/alipay.jpeg
link:
text: alipay
相关文章推荐

相关文章推荐的原理是根据文章 tags 的比重來推荐

修改主题配置文件 butterfly.yml

1
2
3
4
related_post:
enable: true
limit: 6 # 显示推荐文章的数目
date_type: created # or created or updated 文章日期显示创建日或者更新日
页脚自定义脚本

修改主题配置文件 butterfly.yml

1
footer_custom_text: Hi, welcome to my <a href="https://bambooxking.me/">blog</a>!
夜间模式

修改主题配置文件 butterfly.yml

1
2
3
4
5
6
# dark mode
darkmode:
enable: true
# dark mode和 light mode切換按鈕
button: true
autoChangeMode: false
侧边栏设置

修改主题配置文件 butterfly.yml

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
aside:
enable: true
mobile: true # 手机页面( 显示宽度 < 768px )是否显示aside內容
position: right # 侧边栏位置: left or right
card_author:
enable: true
description:
card_announcement:
enable: true
content: This is my Blog
card_recent_post:
enable: true
limit: 5 # if set 0 will show all
card_categories:
enable: true
limit: 8 # if set 0 will show all
expand: none # none/true/false
card_tags:
enable: true
limit: 40 # if set 0 will show all
color: false
card_archives:
enable: true
type: monthly # yearly or monthly
format: MMMM YYYY # eg: YYYY年MM月
order: -1 # Sort of order. 1, asc for ascending; -1, desc for descending
limit: 8 # if set 0 will show all
card_webinfo: true
Note (Bootstrap Callout)

修改主题配置文件 butterfly.yml

1
2
3
4
5
6
7
8
9
10
11
12
note:
# Note tag style values:
# - simple bs-callout old alert style. Default.
# - modern bs-callout new (v2-v3) alert style.
# - flat flat callout style with background, like on Mozilla or StackOverflow.
# - disabled disable all CSS styles import of note tag.
style: simple
icons: false
border_radius: 3
# Offset lighter of background in % for modern and flat styles (modern: -12 | 12; flat: -18 | 6).
# Offset also applied to label tag variables. This option can work with disabled note tag.
light_bg_offset: 0

用法

1
2
3
4
5
6
7
8
{% note [class] [no-icon] %}
Any content (support inline tags too.io).
{% endnote %}

[class] : default | primary | success | info | warning | danger.
[no-icon] : Disable icon in note.

All parameters are optional.

例如

default 提示块标签

primary 提示块标签

success 提示块标签

info 提示块标签

warning 提示块标签

danger 提示块标签

tag-hide

如果你想把一些文字、內容隐藏起來,並提供按钮让用户点击显示。可以使用这个标签外挂。

写法

1
{% hideInline content,display,bg,color %}

content: 文本內容 ( content 不能包含英文逗号,可用 &sbquo;)

display: 按钮显示的文字 (可选)

bg: 按钮的背景颜色 (可选)

color: 按钮文字的颜色 (可选)

例如

哪个英文字母最酷? 因为西裝裤(C裝酷)

门里站着一个人?

mermaid

mermaid 标签不允许嵌套与一些隐藏属性的标签外挂,例如: tag-hide 內的标签外挂和 tabs 标签外挂,这会导致 mermaid 图示无法正常显示,使用时请留意。

请不要压缩 html 代码,不然会导致 mermaid 显示异常。

使用 mermaid 标签可以绘制 Flowchart(流程图)、Sequence diagram(時序图 )、Class Diagram(类别图)、State Diagram(状态图)、Gantt(甘特图)和 Pie Chart(圆形图),具体可以查看 mermaid 文档

修改主题配置文件 butterfly.yml

1
2
3
4
mermaid:
enable: true
# built-in themes: default/forest/dark/neutral
theme: default

写法

1
2
3
{% mermaid %}
內容
{% endmermaid %}

例如

1
2
3
4
5
6
7
8
{% mermaid %}
pie
title Key elements in Product X
"Calcium" : 42.96
"Potassium" : 50.05
"Magnesium" : 10.01
"Iron" : 5
{% endmermaid %}
Tabs

使用方法

  • Unique name: 标签块标签的唯一名,不带逗号。将在#id中用作每个标签及其索引号的前缀,如果名称中包含空格,则为生成#id,所有空格将替换为破折号。仅对于当前帖子/页面的URL必须是唯一的!
  • [index]: 活动标签的索引号。如果未指定,将选择第一个标签(1)。如果index为-1,则不会选择任何选项卡。 可选项。
  • [Tab caption]: 当前标签的标题。如果未指定标题,则带有制表符索引后缀的唯一名称将用作制表符的标题;如果未指定标题,但指定了图标,则标题将为空。可选项。
  • [@icon]: FontAwesome 图标名称。例如: fas fa-font。可选项。
1
2
3
4
5
{% tabs Unique name, [index] %}
<!-- tab [Tab caption] [@icon] -->
Any content (support inline tags too).
<!-- endtab -->
{% endtabs %}

例如

tab名字為第一個Tab

只有圖標 沒有Tab名字

名字+icon

Button

使用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{% btn [url],[text],[icon],[color] [style] [layout] [position] [size] %}

[url] : 鏈接
[text] : 按鈕文字
[icon] : [可選] 圖標
[color] : [可選] 按鈕背景顔色(默認style時)
按鈕字體和邊框顔色(outline時)
default/blue/pink/red/purple/orange/green
[style] : [可選] 按鈕樣式 默認實心
outline/留空
[layout] : [可選] 按鈕佈局 默認為line
block/留空
[position] : [可選] 按鈕位置 前提是設置了layout為block 默認為左邊
center/right/留空
[size] : [可選] 按鈕大小
larger/留空

例如

This is my website, click the button bambooxking
This is my website, click the button bambooxking
This is my website, click the button

bambooxking bambooxking bambooxking bambooxking bambooxking bambooxking bambooxking bambooxking bambooxking bambooxking
搜索系统

安装插件 hexo-algoliasearch

1
npm install hexo-algoliasearch --save

官网注册账号,新建 index,打开 API Keys 页面,里面的信息等会需要写到hexo的配置文件中。

在 Hexo 根目录 _config.yml 里配置 plugins

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
plugins:
- hexo-algoliasearch

algolia:
appId: "61RS0UBF68"
apiKey: "eaf0572f9db828b7378d43c1ea30cf38"
adminApiKey: "1fd7e0feb7c2bdd43972475ad799dd13"
chunkSize: 5000
indexName: "hexo-comment"
fields:
- content:strip:truncate,0,500
- excerpt:strip
- gallery
- permalink
- photos
- slug
- tags
- title
网站背景

修改主题配置文件 butterfly.yml

1
2
3
4
5
# 图片格式 background: url(http://xxxxxx.com/xxx.jpg)
# 颜色 background: '#49B202'
# 留空 显示白色
# background: '#49B202'
background: url(https://i.loli.net/2019/09/09/5oDRkWVKctx2b6A.png)
页脚背景

footer 的背景會与 top_img 的一致,当设置 false 時,將与主题色一致。

修改主题配置文件 butterfly.yml

1
2
# footer是否显示图片背景(与top_img一致)
footer_bg: true
背景特效

修改主题配置文件 butterfly.yml

  • 静止彩带

    1
    2
    3
    4
    5
    6
    7
    canvas_ribbon:
    enable: true
    size: 150
    alpha: 0.6
    zIndex: -1
    click_to_change: true # 设置是否每次点击都更换彩带
    mobile: false # false 手机端不显示 true 手机端显示
  • 动态彩带

    1
    2
    3
    canvas_ribbon_piao:
    enable: true
    mobile: false # false 手机端不显示 true 手机端显示
  • canvas_nest

    1
    2
    3
    4
    5
    6
    7
    canvas_nest:
    enable: true
    color: '0,0,255' #color of lines, default: '0,0,0'; RGB values: (R,G,B).(note: use ',' to separate.)
    opacity: 0.7 # the opacity of line (0~1), default: 0.5.
    zIndex: -1 # z-index property of the background, default: -1.
    count: 99 # the number of lines, default: 99.
    mobile: false # false 手机端不显示 true 手机端显示
鼠标点击效果

修改主题配置文件 butterfly.yml

  • 烟花

    1
    2
    3
    4
    # -1 代表烟火效果在底部; 9999 代表烟火效果在前面
    fireworks:
    enable: true
    zIndex: 9999 # -1 or 9999
  • 爱心

    1
    2
    # 点击出现爱心
    click_heart: true
  • 点击出现文字

    1
    2
    3
    4
    5
    6
    7
    8
    # 点击出現文字,文字可自行修改
    ClickShowText:
    enable: true
    text:
    - I
    - LOVE
    - YOU
    fontSize: 15px
页面美化

修改主题配置文件 butterfly.yml

1
2
3
4
5
6
# 美化页面显示
beautify:
enable: true
field: site # site/post
title-prefix-icon: '\f0c1'
title-prefix-icon-color: "#F47466"
网站副标题

修改主题配置文件 butterfly.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 主页subtitle
subtitle:
enable: true
# 打字效果
effect: true
# 循环或者只打字一次
loop: true
# source調用第三方服務
# source: false 關閉調用
# source: 1 調用搏天api的隨機語錄(簡體) https://api.btstu.cn/
# source: 2 調用一言網的一句話(簡體) https://hitokoto.cn/
# source: 3 調用一句網(簡體) http://yijuzhan.com/
# source: 4 調用今日詩詞(簡體) https://www.jinrishici.com/
# subtitle 會先顯示 source , 再顯示 sub 的內容
source: 4
# 如果有英文逗號' , ',請使用轉義字元 &#44;
# 如果有英文雙引號' " ',請使用轉義字元 &quot;
# 開頭不允許轉義字元,如需要,請把整個句子用雙引號包住
# 例如 ”&quotNever put off till tomorrow what you can do today&quot"
# 如果關閉打字效果,subtitle只會顯示sub的第一行文字
sub:
- 今日事&#44;今日毕
- Never put off till tomorrow what you can do today
字数统计

安装插件 hexo-wordcount

1
npm install hexo-wordcount --save

修改主题配置文件 butterfly.yml

1
2
3
4
5
wordcount:
enable: true
post_wordcount: true
min2read: true
total_wordcount: true
Snackbar 弹窗

修改主题配置文件 butterfly.yml

1
2
3
4
5
6
7
8
9
# Snackbar 弹窗
# https://github.com/polonel/SnackBar
# position 弹窗位置
# 可选 top-left / top-center / top-right / bottom-left / bottom-center / bottom-right
snackbar:
enable: true
position: bottom-left
bg_light: '#49b1f5' #light mode 时弹窗背景
bg_dark: '#2d3035' #dark mode 时弹窗背景
Gulp 压缩
  • 安装

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    npm install --global gulp-cli

    # 压缩 HTML 用
    npm install gulp-htmlclean --save-dev
    npm install --save gulp-htmlmin

    # 压缩 CSS 用
    npm install gulp-clean-css --save-dev

    # 压缩 JS 用
    npm install --save-dev gulp-uglify
    npm install --save-dev gulp-babel @babel/core @babel/preset-env

    # 压缩图片用
    npm install --save-dev gulp-imagemin
  • 创建 gulpfile 文件

    在 Hexo 的根目录,创建一個 gulpfile.js 文件

    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
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    var gulp = require('gulp')
    var cleanCSS = require('gulp-clean-css')
    var htmlmin = require('gulp-htmlmin')
    var htmlclean = require('gulp-htmlclean')
    var imagemin = require('gulp-imagemin')
    // tester (如果使用tester,把下面4行前面的//去掉)
    // var uglifyjs = require('terser')
    // var composer = require('gulp-uglify/composer')
    // var pump = require('pump')
    // var minify = composer(uglifyjs, console)

    // babel (如果不是使用bebel,把下面兩行註釋掉)
    var uglify = require('gulp-uglify')
    var babel = require('gulp-babel')

    // minify js - babel( 如果不是使用bebel,把下面註釋掉)
    gulp.task('compress', () =>
    gulp.src(['./public/**/*.js', '!./public/**/*.min.js'])
    .pipe(babel({
    presets: ['@babel/preset-env']
    }))
    .pipe(uglify().on('error', function (e) {
    console.log(e)
    }))
    .pipe(gulp.dest('./public'))
    )

    // minify js - tester (如果使用tester,把下面前面的//去掉)
    // gulp.task('compress', function (cb) {
    // var options = {}
    // pump([
    // gulp.src(['./public/**/*.js', '!./public/**/*.min.js']),
    // minify(options),
    // gulp.dest('./public')
    // ],
    // cb
    // )
    // })

    // css
    gulp.task('minify-css', () => {
    return gulp.src('./public/**/*.css')
    .pipe(cleanCSS())
    .pipe(gulp.dest('./public'))
    })

    // 壓縮 public 目錄內 html
    gulp.task('minify-html', () => {
    return gulp.src('./public/**/*.html')
    .pipe(htmlclean())
    .pipe(htmlmin({
    removeComments: true, // 清除 HTML 註釋
    collapseWhitespace: true, // 壓縮 HTML
    collapseBooleanAttributes: true, // 省略布爾屬性的值 <input checked="true"/> ==> <input />
    removeEmptyAttributes: true, // 刪除所有空格作屬性值 <input id="" /> ==> <input />
    removeScriptTypeAttributes: true, // 刪除 <script> 的 type="text/javascript"
    removeStyleLinkTypeAttributes: true, // 刪除 <style> 和 <link> 的 type="text/css"
    minifyJS: true, // 壓縮頁面 JS
    minifyCSS: true, // 壓縮頁面 CSS
    minifyURLs: true
    }))
    .pipe(gulp.dest('./public'))
    })

    // 壓縮 public/uploads 目錄內圖片
    gulp.task('minify-images', async () => {
    gulp.src('./public/img/**/*.*')
    .pipe(imagemin({
    optimizationLevel: 5, // 類型:Number 預設:3 取值範圍:0-7(優化等級)
    progressive: true, // 類型:Boolean 預設:false 無失真壓縮jpg圖片
    interlaced: false, // 類型:Boolean 預設:false 隔行掃描gif進行渲染
    multipass: false // 類型:Boolean 預設:false 多次優化svg直到完全優化
    }))
    .pipe(gulp.dest('./public/img'))
    })

    // 執行 gulp 命令時執行的任務
    gulp.task('default', gulp.parallel(
    'compress', 'minify-css', 'minify-html', 'minify-images'
    ))

    注意: 如果有使用到 Butterfly 主題提供的 mermaid 标签外挂,那需要把 52 行.pipe(htmlclean()) 注释掉,同時,把 55 行的 collapseWhitespace: true, 改为 false。

  • 运行

    hexo g 之后运行 gulp 就行。

PWA

PWA(Progressive Web App)是一种理念,使用多种技术来增强web app的功能,可以让网站的体验变得更好,能够模拟一些原生功能,比如通知推送。在移动端利用标准化框架,让网页应用呈现和原生应用相似的体验。

  • butterfly.yml 中开启 pwa 选项

    1
    2
    3
    4
    5
    6
    7
    8
    pwa:
    enable: true
    manifest: /img/pwa/manifest.json
    theme_color: "#fff"
    apple_touch_icon: /img/pwa/apple-touch-icon.png
    favicon_32_32: /img/pwa/32.png
    favicon_16_16: /img/pwa/16.png
    mask_icon: /img/pwa/safari-pinned-tab.svg
  • 在 Hexo 的 source 目录中创建 manifest.json 文件。

    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
    {
    "name": "string", //應用全稱
    "short_name": "Junzhou", //應用簡稱
    "theme_color": "#49b1f5", //匹配瀏覽器的地址欄顏色
    "background_color": "#49b1f5",//加載應用時的背景色
    "display": "standalone",//首選顯示模式 其他選項有:fullscreen,minimal-ui,browser
    "scope": "/",
    "start_url": "/",
    "icons": [ //該數組指定icons圖標參數,用來時適配不同設備(需為png,至少包含一個192px*192px的圖標)
    {
    "src": "images/pwaicons/36.png", //圖標文件的目錄,需在source/目錄下自行創建。
    "sizes": "36x36",
    "type": "image/png"
    },
    {
    "src": "images/pwaicons/48.png",
    "sizes": "48x48",
    "type": "image/png"
    },
    {
    "src": "images/pwaicons/72.png",
    "sizes": "72x72",
    "type": "image/png"
    },
    {
    "src": "images/pwaicons/96.png",
    "sizes": "96x96",
    "type": "image/png"
    },
    {
    "src": "images/pwaicons/144.png",
    "sizes": "144x144",
    "type": "image/png"
    },
    {
    "src": "images/pwaicons/192.png",
    "sizes": "192x192",
    "type": "image/png"
    },
    {
    "src": "images/pwaicons/512.png",
    "sizes": "512x512",
    "type": "image/png"
    }
    ],
    "splash_pages": null //配置自定義啟動動畫。
    }
  • 安装插件

    1
    npm install workbox-build gulp --save-dev
  • 创建 gulpfile.js 文件

    在 Hexo 的根目录,创建一個个 gulpfile.js 文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    const gulp = require("gulp");
    const workbox = require("workbox-build");

    gulp.task('generate-service-worker', () => {
    return workbox.injectManifest({
    swSrc: './sw-template.js',
    swDest: './public/sw.js',
    globDirectory: './public',
    globPatterns: [
    "**/*.{html,css,js,json,woff2}"
    ],
    modifyURLPrefix: {
    "": "./"
    }
    });
    });

    gulp.task("build", gulp.series("generate-service-worker"));
  • 创建 sw-template.js 文件

    在 Hexo 的根目录,创建一个 sw-template.js 文件

    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
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    const workboxVersion = '5.1.3';

    importScripts(`https://storage.googleapis.com/workbox-cdn/releases/${workboxVersion}/workbox-sw.js`);

    workbox.core.setCacheNameDetails({
    prefix: "your name"
    });

    workbox.core.skipWaiting();

    workbox.core.clientsClaim();

    workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);

    workbox.precaching.cleanupOutdatedCaches();

    // Images
    workbox.routing.registerRoute(
    /\.(?:png|jpg|jpeg|gif|bmp|webp|svg|ico)$/,
    new workbox.strategies.CacheFirst({
    cacheName: "images",
    plugins: [
    new workbox.expiration.ExpirationPlugin({
    maxEntries: 1000,
    maxAgeSeconds: 60 * 60 * 24 * 30
    }),
    new workbox.cacheableResponse.CacheableResponsePlugin({
    statuses: [0, 200]
    })
    ]
    })
    );

    // Fonts
    workbox.routing.registerRoute(
    /\.(?:eot|ttf|woff|woff2)$/,
    new workbox.strategies.CacheFirst({
    cacheName: "fonts",
    plugins: [
    new workbox.expiration.ExpirationPlugin({
    maxEntries: 1000,
    maxAgeSeconds: 60 * 60 * 24 * 30
    }),
    new workbox.cacheableResponse.CacheableResponsePlugin({
    statuses: [0, 200]
    })
    ]
    })
    );

    // Google Fonts
    workbox.routing.registerRoute(
    /^https:\/\/fonts\.googleapis\.com/,
    new workbox.strategies.StaleWhileRevalidate({
    cacheName: "google-fonts-stylesheets"
    })
    );
    workbox.routing.registerRoute(
    /^https:\/\/fonts\.gstatic\.com/,
    new workbox.strategies.CacheFirst({
    cacheName: 'google-fonts-webfonts',
    plugins: [
    new workbox.expiration.ExpirationPlugin({
    maxEntries: 1000,
    maxAgeSeconds: 60 * 60 * 24 * 30
    }),
    new workbox.cacheableResponse.CacheableResponsePlugin({
    statuses: [0, 200]
    })
    ]
    })
    );

    // Static Libraries
    workbox.routing.registerRoute(
    /^https:\/\/cdn\.jsdelivr\.net/,
    new workbox.strategies.CacheFirst({
    cacheName: "static-libs",
    plugins: [
    new workbox.expiration.ExpirationPlugin({
    maxEntries: 1000,
    maxAgeSeconds: 60 * 60 * 24 * 30
    }),
    new workbox.cacheableResponse.CacheableResponsePlugin({
    statuses: [0, 200]
    })
    ]
    })
    );

    workbox.googleAnalytics.initialize();

    把 prefix 修改为你博客的名字(英文)。

  • 添加 js 进主题

    配置 butterfly.yml, 添加需要的 css 和 js

    1
    2
    3
    4
    5
    inject:
    head:
    - '<style type="text/css">.app-refresh{position:fixed;top:-2.2rem;left:0;right:0;z-index:99999;padding:0 1rem;font-size:15px;height:2.2rem;transition:all .3s ease}.app-refresh-wrap{display:flex;color:#fff;height:100%;align-items:center;justify-content:center}.app-refresh-wrap a{color:#fff;text-decoration:underline;cursor:pointer}</style>'
    bottom:
    - '<div class="app-refresh" id="app-refresh"> <div class="app-refresh-wrap"> <label>✨ 網站已更新最新版本 👉</label> <a href="javascript:void(0)" onclick="location.reload()">點擊刷新</a> </div></div><script>function showNotification(){if(GLOBAL_CONFIG.Snackbar){var t="light"===document.documentElement.getAttribute("data-theme")?GLOBAL_CONFIG.Snackbar.bgLight:GLOBAL_CONFIG.Snackbar.bgDark,e=GLOBAL_CONFIG.Snackbar.position;Snackbar.show({text:"已更新最新版本",backgroundColor:t,duration:5e5,pos:e,actionText:"點擊刷新",actionTextColor:"#fff",onActionClick:function(t){location.reload()}})}else{var o=`top: 0; background: ${"light"===document.documentElement.getAttribute("data-theme")?"#49b1f5":"#1f1f1f"};`;document.getElementById("app-refresh").style.cssText=o}}"serviceWorker"in navigator&&(navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("controllerchange",function(){showNotification()}),window.addEventListener("load",function(){navigator.serviceWorker.register("/sw.js")}));</script>'

maupassant-hexo

主题获取

1
git clone git@github.com:wzx3/maupassant-hexo.git themes/maupassant

主题生效

博客工程根目录下,修改 _config.yml

1
theme: maupassant

初始化主题

1
2
3
hexo clean   //清除缓存文件 (db.json) 和已生成的静态文件 (public)
hexo g //生成缓存和静态文件
hexo d //重新部署到服务器

自定义配置

编辑主题配置文件: themes/maupassant/_config.yml

Disqus评论相关参数
1
disqus: wangzhuxing ## Your disqus_shortname, e.g. username

在文章的 front-matter 中添加 comments: false 即可关闭, 默认开启。

  • gitalk评论配置

    • 需要 Github Application,如果没有 点击这里申请Authorization callback URL 填写你主页地址,比如我的就是 https://bambooxking.github.io/,其他都随意。
    • 记住Client IDClient Secret
    • 第一次访问需要登陆,github账号。
    • 参考链接:hexo博客中添加gitalk评论插件
  • 站内搜索

    • 方式一: 使用self_search

      这种方式我自己本地可以进行站内搜索, 部署推送到github上无法搜索, 很奇怪。

      1
      2
      google_search: false ## Use Google search, true/false.
      self_search: true ## Use a jQuery-based local search engine, true/false.

      关闭谷歌搜索, 开启站内搜索。

      需安装 hexo-generator-searchdb

      1
      npm install hexo-generator-searchdb  --save
    • 方式二: 使用swiftype

      这种方式是直接由swiftype爬虫抓取github.io上的页面内容搜索得到的。

      • 登录Swiftype官网, 注册(可直接用谷歌账号登录)。

      • 创建搜索引擎

        CREATE A NEW ENGINE

      • 输入你的github.io, 记得末尾要带/, 然后取个名字, 创建成功。

        输入github.io

      • 安装搜索引擎

        安装搜索引擎

        底下会提示: 网站搜索爬虫正在爬虫你的网页, 在完成之前无法进行样式配置和站点搜索。

        大约等个十几分钟左右, 底下提示栏消失, 这时候Install Search页面会多出一段js代码:

        swiftype_key就在这段代码的底下:

        将其复制到主题配置设置

        1
        swiftype:  ## Your swiftype_key, e.g. m7b11ZrsT8Me7gzApciT
      • 重新部署并推送远端即可完成站内搜索配置

        1
        hexo clean && hexo g && hexo d
  • 添加分享按钮

    1
    shareto: true ## If you want to use the share button please set the value to true, and you must have hexo-helper-qrcode installed.

    需安装 hexo-helper-qrcode

    1
    npm install hexo-helper-qrcode  --save
  • 是否开启页面访问计数

    1
    busuanzi: true ## If you want to use Busuanzi page views please set the value to true.
  • 是否开启文章字数统计、阅读时长显示

    1
    wordcount: true ## If you want to display the word counter and the reading time expected to spend of each post please set the value to true, and you must have hexo-wordcount installed.
  • 是否开启捐赠按钮

    1
    2
    3
    4
    donate:
    enable: true ## If you want to display the donate button after each post, please set the value to true and fill the following items on your need. You can also enable donate button in a page by adding a "donate: true" item to the front-matter.
    alipay_qr: /img/alipay.jpg ## Path of Alipay QRcode image, e.g. /img/AliPayQR.png
    wechat_qr: /img/wechatpay.jpg ## Path of Wechat QRcode image, e.g. /img/WeChatQR.png
  • 是否在末尾显示原文作者

    1
    2
    3
    4
    post_copyright:
    enable: true ## If you want to display the copyright info after each post, please set the value to true and fill the following items on your need.
    author: 王竹兴 ## Your author name, e.g. tufu9441
    copyright_text: 本文为博主原创文章,转载请附上博文链接! ## Your copyright text, e.g. The author owns the copyright, please indicate the source reproduced.