Hexo博客搭建


Hexo介绍

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

目录结构

  • node_modules是hexo插件安装的地方
  • scaffolds放一些通用的MarkDown模板
  • source就是编写的博客文件,格式为 .md
  • public存放生成的静态页面,上传服务器时只需要上传这个文件夹即可
  • themes下存放的就是主题文件
  • _config.yml是博客站点的配置文件

详情可查看Hexo官方主页 https://hexo.io/zh-cn/docs

Hexo安装

环境安装

  • Node.js
  • Git
  • 完成后使用node -vnpm -v检查是否安装成功

Hexo安装

  • 新建一个文件夹blog,命令行进入文件夹
npm install -g hexo-cli
  • 使用hexo -v检查是否安装成功
  • 初始化hexo
hexo init
npm install
  • 完成后使用命令
hexo g && hexo s
  • 生成页面并启动服务

Hexo优化

主题

git clone https://github.com/blinkfox/hexo-theme-matery.git
  • 编辑站点配置文件_config.yml,修改主题
# Extensions
## Plugins: https://hexo.io/plugins/
## Themes: https://hexo.io/themes/
theme: hexo-theme-matery

安装插件

cd 到博客根目录下

npm install hexo-generator-feed --save                 #RSS
npm install hexo-generator-search --save               #搜索
npm install hexo-generator-sitemap --save              #sitemap
npm install hexo-generator-baidu-sitemap --save        #百度sitemap
npm install hexo-prism-plugin --save                   #代码高亮     
npm install hexo-wordcount --save                      #文章字数统计
npm install hexo-filter-nofollow --save                #nofollow
npm install hexo-filter-github-emojis --save           #emoji表情支持
npm install hexo-deployer-git --save                    #部署github
npm i hexo-permalink-pinyin --save                       #中文链接转拼音
npm install --save hexo-helper-live2d                   #Live 2D
npm install hexo-abbrlink --save                       #文章永久链接

1) RSS

  • 在根目录下的_config.yml中添加对应配置
feed:
  type: atom
  path: atom.xml
  limit: 20
  hub:
  content:
  content_limit: 140
  content_limit_delim: ' '
  order_by: -date

2) 搜索

  • 在根目录下的_config.yml中添加对应配置
search:
  path: search.xml
  field: post

3) 代码高亮

修改根目录下_config.yml文件中highlight.enable的值为false

highlight:
  enable:
falseprism_plugin:
  mode: 'preprocess'    # realtime/preprocess
  theme: 'tomorrow'
  line_number: false    # default false
  custom_css:

更多代码高亮主题,可以参考 https://yafine-blog.cn/posts/f295.html

4) 字数统计

  • 在根目录下的_config.yml中添加对应配置
postInfo:
  date: true
  update: false
  wordCount: false  # 设置文章字数统计为 true.
  totalCount: false # 设置站点文章总字数统计为 true.
  min2read: false   # 阅读时长.
  readCount: false  # 阅读次数.

5) Live 2D 模型

  • 安装模块
npm install --save hexo-helper-live2d
  • 选择模型(共22款模型)
live2d-widget-model-chitose
live2d-widget-model-epsilon2_1
live2d-widget-model-gf
live2d-widget-model-haru/01 (use npm install --save live2d-widget-model-haru)
live2d-widget-model-haru/02 (use npm install --save live2d-widget-model-haru)
live2d-widget-model-haruto
live2d-widget-model-hibiki
live2d-widget-model-hijiki
live2d-widget-model-izumi
live2d-widget-model-koharu
live2d-widget-model-miku
live2d-widget-model-ni-j
live2d-widget-model-nico
live2d-widget-model-nietzsche
live2d-widget-model-nipsilon
live2d-widget-model-nito
live2d-widget-model-shizuku
live2d-widget-model-tororo
live2d-widget-model-tsumiki
live2d-widget-model-unitychan
live2d-widget-model-wanko
live2d-widget-model-z16
  • 安装模型
npm install 模型名字
  • 在根目录或者主题下的_config.yml中添加对应配置(如下例子)
live2d:
  enable: true
  scriptFrom: local
  pluginRootPath: live2dw/
  pluginJsPath: lib/
  pluginModelPath: assets/
  tagMode: false
  log: false
  model:
    use: live2d-widget-model-wanko
  display:
    position: right
    width: 150
    height: 300
  mobile:
    show: true
  react:
    opacity: 0.7

6) 添加樱花特效

themes/matery/source/js目录下新建sakura.js文件,打开这个网址传送门,将内容复制粘贴到sakura.js即可。

然后再themes/matery/layout/layout.ejs文件内添加下面的内容:

<script type="text/javascript">
//只在桌面版网页启用特效
var windowWidth = $(window).width();
if (windowWidth > 768) {
    document.write('<script type="text/javascript" src="/js/sakura.js"><\/script>');
}
</script>

7) 代码压缩

使用方法:

  1. 进入站点根目录下依次执行下面的命令:
# 全局安装gulp模块
npm install gulp -g
# 安装各种小功能模块  执行这步的时候,可能会提示权限的问题,最好以管理员模式执行
npm install gulp gulp-htmlclean gulp-htmlmin gulp-minify-css gulp-uglify gulp-imagemin --save
# 额外的功能模块
npm install gulp-debug gulp-clean-css gulp-changed gulp-if gulp-plumber gulp-babel babel-preset-es2015 del @babel/core --save
  1. 在Hexo根目录新建文件 gulpfile.js,并复制以下内容到文件中,有中文注释,可以根据自己需求修改。(注意:文件名不能错,一定为gulpfile.js,否则会出错!)

注意:这里我没有使用图片压缩功能,需要的请自行根据以下代码更改

开启图片压缩可以把第154行的 "compressImage", 和第165行的 ,"compressImage" 的注释去掉即可

var gulp = require("gulp");
var debug = require("gulp-debug");
var cleancss = require("gulp-clean-css"); //css压缩组件
var uglify = require("gulp-uglify"); //js压缩组件
var htmlmin = require("gulp-htmlmin"); //html压缩组件
var htmlclean = require("gulp-htmlclean"); //html清理组件
var imagemin = require("gulp-imagemin"); //图片压缩组件
var changed = require("gulp-changed"); //文件更改校验组件
var gulpif = require("gulp-if"); //任务 帮助调用组件
var plumber = require("gulp-plumber"); //容错组件(发生错误不跳出任务,并报出错误内容)
var isScriptAll = true; //是否处理所有文件,(true|处理所有文件)(false|只处理有更改的文件)
var isDebug = true; //是否调试显示 编译通过的文件
var gulpBabel = require("gulp-babel");
var es2015Preset = require("babel-preset-es2015");
var del = require("del");
var Hexo = require("hexo");
var hexo = new Hexo(process.cwd(), {}); // 初始化一个hexo对象

// 清除public文件夹
gulp.task("clean", function () {
    return del(["public/**/*"]);
});

// 下面几个跟hexo有关的操作,主要通过hexo.call()去执行,注意return
// 创建静态页面 (等同 hexo generate)
gulp.task("generate", function () {
    return hexo.init().then(function () {
        return hexo
            .call("generate", {
                watch: false
            })
            .then(function () {
                return hexo.exit();
            })
            .catch(function (err) {
                return hexo.exit(err);
            });
    });
});

// 启动Hexo服务器
gulp.task("server", function () {
    return hexo
        .init()
        .then(function () {
            return hexo.call("server", {});
        })
        .catch(function (err) {
            console.log(err);
        });
});

// 部署到服务器
gulp.task("deploy", function () {
    return hexo.init().then(function () {
        return hexo
            .call("deploy", {
                watch: false
            })
            .then(function () {
                return hexo.exit();
            })
            .catch(function (err) {
                return hexo.exit(err);
            });
    });
});

// 压缩public目录下的js文件
gulp.task("compressJs", function () {
    return gulp
        .src(["./public/**/*.js", "!./public/libs/**"]) //排除的js
        .pipe(gulpif(!isScriptAll, changed("./public")))
        .pipe(gulpif(isDebug, debug({ title: "Compress JS:" })))
        .pipe(plumber())
        .pipe(
            gulpBabel({
                presets: [es2015Preset] // es5检查机制
            })
        )
        .pipe(uglify()) //调用压缩组件方法uglify(),对合并的文件进行压缩
        .pipe(gulp.dest("./public")); //输出到目标目录
});

// 压缩public目录下的css文件
gulp.task("compressCss", function () {
    var option = {
        rebase: false,
        //advanced: true, //类型:Boolean 默认:true [是否开启高级优化(合并选择器等)]
        compatibility: "ie7" //保留ie7及以下兼容写法 类型:String 默认:''or'*' [启用兼容模式; 'ie7':IE7兼容模式,'ie8':IE8兼容模式,'*':IE9+兼容模式]
        //keepBreaks: true, //类型:Boolean 默认:false [是否保留换行]
        //keepSpecialComments: '*' //保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀,如果不加这个参数,有可能将会删除你的部分前缀
    };
    return gulp
        .src(["./public/**/*.css", "!./public/**/*.min.css"]) //排除的css
        .pipe(gulpif(!isScriptAll, changed("./public")))
        .pipe(gulpif(isDebug, debug({ title: "Compress CSS:" })))
        .pipe(plumber())
        .pipe(cleancss(option))
        .pipe(gulp.dest("./public"));
});

// 压缩public目录下的html文件
gulp.task("compressHtml", function () {
    var cleanOptions = {
        protect: /<\!--%fooTemplate\b.*?%-->/g, //忽略处理
        unprotect: /<script [^>]*\btype="text\/x-handlebars-template"[\s\S]+?<\/script>/gi //特殊处理
    };
    var minOption = {
        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"
        removeComments: true, //清除HTML注释
        minifyJS: true, //压缩页面JS
        minifyCSS: true, //压缩页面CSS
        minifyURLs: true //替换页面URL
    };
    return gulp
        .src("./public/**/*.html")
        .pipe(gulpif(isDebug, debug({ title: "Compress HTML:" })))
        .pipe(plumber())
        .pipe(htmlclean(cleanOptions))
        .pipe(htmlmin(minOption))
        .pipe(gulp.dest("./public"));
});

// 压缩 public/medias 目录内图片
gulp.task("compressImage", function () {
    var option = {
        optimizationLevel: 5, //类型:Number 默认:3 取值范围:0-7(优化等级)
        progressive: true, //类型:Boolean 默认:false 无损压缩jpg图片
        interlaced: false, //类型:Boolean 默认:false 隔行扫描gif进行渲染
        multipass: false //类型:Boolean 默认:false 多次优化svg直到完全优化
    };
    return gulp
        .src("./public/medias/**/*.*")
        .pipe(gulpif(!isScriptAll, changed("./public/medias")))
        .pipe(gulpif(isDebug, debug({ title: "Compress Images:" })))
        .pipe(plumber())
        .pipe(imagemin(option))
        .pipe(gulp.dest("./public"));
});
// 执行顺序: 清除public目录 -> 产生原始博客内容 -> 执行压缩混淆 -> 部署到服务器
gulp.task(
    "build",
    gulp.series(
        "clean",
        "generate",
        "compressHtml",
        "compressCss",
        "compressJs",
        // "compressImage",
        gulp.parallel("deploy")
    )
);

// 默认任务
gulp.task(
    "default",
    gulp.series(
        "clean",
        "generate",
        gulp.parallel("compressHtml", "compressCss", "compressJs"/*,"compressImage"*/)
    )
);
//Gulp4最大的一个改变就是gulp.task函数现在只支持两个参数,分别是任务名和运行任务的函数
  1. 以后执行的方式有2种
  • 直接在Hexo根目录执行 gulp或者 gulp default ,这个命令相当于 hexo cl&&hexo g 并且再把代码和图片压缩
  • 在Hexo根目录执行 gulp build ,这个命令与第1种相比是:在最后又加了个 hexo d ,等于说生成、压缩文件后又帮你自动部署了

8) 文章永久链接

  • Hexo修改永久链接的默认格式,方便SEO.

  • 在根目录下的_config.yml中添加对应配置

abbrlink:
    alg: crc16   #算法: crc16(default) and crc32
    rep: hex     #进制: dec(default) and hex: dec #输出进制:十进制和十六进制,默认为10进制。丨dec为十进制,hex为十六进制
    drafts: false   #(true)Process draft,(false)Do not process draft. false(default) 
  # Generate categories from directory-tree
  # depth: the max_depth of directory-tree you want to generate, should > 0
  auto_category:
     enable: true  #true(default)
     depth:        #3(default)
  auto_title: false #enable auto title, it can auto fill the title by path
  auto_date: false #enable auto date, it can auto fill the date by time today
  force: false #enable force mode,in this mode, the plugin will ignore the cache, and calc the abbrlink for every post even it already had abbrlink.
  • 再将根目录下的_config.ymlpermalink值修改为:
permalink: posts/:abbrlink.html  # 此处可以自己设置,也可以直接使用 :/abbrlink

生成文章的链接格式就会是如下样例(官方样例):

crc16 & hex
https://post.zz173.com/posts/66c8.html

crc16 & dec
https://post.zz173.com/posts/65535.html
crc32 & hex
https://post.zz173.com/posts/8ddf18fb.html

crc32 & dec
https://post.zz173.com/posts/1690090958.html

生成完后,原 md 文件的 Front-matter 内会增加 abbrlink 字段,值为生成的 ID 。这个字段确保了在我们修改了 Front-matter 内的博客标题 title 或创建日期 date 字段之后而不会改变链接地址。

9) 添加自定义页面

以我配置的聚宝盒为例

  • 首先在站点目录下的 source文件夹下新建box文件夹,文件名可以自定义;然后将index.html放入 box文件夹下;再在主题目录下的_config.yml中添加如下配置:
  聚宝盒:
    url: /box
    icon: fas fa-location-arrow
  • 然后在根目录下的_config.yml中,找到skip_render,在后面添加如下属性:(重点)
skip_render: aboutme/**  # 其意思为在对文件进行渲染时跳过aboutme文件下的所有文件
  • 如果添加需要跳过多个目录下的文件时,配置如下:
skip_render: 
    - aboutme/** 
    - box/**
    - 2020/**

知道方法后,你可以添加你自己想要添加的页面,让你的博客内容更加充实。

评论系统

  • 在主题目录下的_config.yml中添加对应配置
gitalk:
  enable: true
  owner: github名字
  repo: github博客名
  oauth: 
    clientId: 生成
    clientSecret: 生成 
  admin: github名字

SEO 优化

请参考这篇博文: https://blog.sky03.cn/posts/42790.html#toc-heading-18


文章作者: nfLJ
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 nfLJ !
评论
 上一篇
CentOS_7配置静态IP CentOS_7配置静态IP
Centos 7 配置静态IP1.打开VMware,进入虚拟网络编辑器 2.进行如下配置 3.进入虚拟机设置 4.进行如下设置 5.进入CentOS7终端su root //以管理员身份 vim /etc/sysconfig/netwo
2020-06-13
本篇 
Hexo博客搭建 Hexo博客搭建
Hexo介绍Hexo 是一个快速、简洁且高效的博客框架。Hexo 使用 Markdown(或其他渲染引擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。 目录结构 node_modules是hexo插件安装的地方 scaffolds放
2020-06-11
  目录