Hexo + Github 我的博客設置以及優化

原文地址: Hexo + Github 我的博客設置以及優化javascript

1、博客設置

分類、標籤雲、關於等頁面

在站點目錄下分別執行:css

hexo new page "categories"  # 新增分類
hexo new page "tags"        # 新增標籤
hexo new page "about"       # 新增關於

能夠在對應的 index.md 中添加 comments: false 來關閉評論功能;
而後再主題配置文件 _config.yml 中打開註釋:html

menu:
  首頁: / || home
  關於: /about/ || user
  標籤: /tags/ || tags
  分類: /categories/ || th
  歸檔: /archives/ || archive

網站背景 canvas_nest[背景多個點間隨機連線]

src: theme-next-canvas-nestjava

主題配置文件中配置腳本:android

canvas_nest: //cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1.0.0/canvas-nest.min.js
  canvas_nest_nomobile: //cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1.0.0/canvas-nest-nomobile.min.js

並啓用:git

canvas_nest:
  enable: true
  onmobile: true # display on mobile or not
  color: "0,0,255" # RGB values, use ',' to separate
  opacity: 0.5 # the opacity of line: 0~1
  zIndex: -1 # z-index property of the background
  count: 99 # the number of lines

信息欄頭像

主題配置文件 _config.yml 中編輯:
avatar: [頭像路徑]github

修改文章底部帶 # 的標籤

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

文章加密訪問

TODO: 發佈後無效
themes/*/layout/_partials/head/head.swig 中在 </script> 前添加代碼:npm

(function(){
  if('{{ page.password }}'){
      if (prompt('請輸入密碼') !== '{{ page.password }}'){
          alert('密碼錯誤');
          history.back();
      }
  }
})();

寫文章時加入:json

---
title: 2018
date: 2018-10-25 16:10:03
password: 123456
---

添加博客項目 README.md, 跳過渲染

在博客配置文件中設置:

skip_render: README.md

字數統計+閱讀時間

src: hexo-symbols-count-time

  1. 安裝包
npm install hexo-symbols-count-time --save
  1. 在博客配置文件中啓用:
symbols_count_time:
  symbols: true
  time: true
  total_symbols: true
  total_time: true
  1. 在主題配置文件中設置:
# 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 # Average Word Length (chars count in word). Default: 4.
    wpm: 275 # Words Per Minute. Default: 275.

聊天模塊 DaoVioce

網站運行時間

themes/layout/_parrials/footer.swing 中添加:

<span id="sitetime"></span>
<script language=javascript>
  function siteTime(){
    window.setTimeout("siteTime()", 1000);
    var seconds = 1000;
    var minutes = seconds * 60;
    var hours = minutes * 60;
    var days = hours * 24;
    var years = days * 365;
    var today = new Date();
    var todayYear = today.getFullYear();
    var todayMonth = today.getMonth()+1;
    var todayDate = today.getDate();
    var todayHour = today.getHours();
    var todayMinute = today.getMinutes();
    var todaySecond = today.getSeconds();
    var t1 = Date.UTC(2018,06,07,12,00,00); // 設置創建網站的時間
    var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
    var diff = t2-t1;
    var diffYears = Math.floor(diff/years);
    var diffDays = Math.floor((diff/days)-diffYears*365);
    var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
    var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
    var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
    document.getElementById("sitetime").innerHTML=" 已運行"+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小時 "+diffMinutes+" 分鐘 "+diffSeconds+" 秒";
  }
  siteTime();
</script>

網站的 favicon

主題配置文件中設置:

# For example, you put your favicons into `hexo-site/source/images` directory.
# Then need to rename & redefine them on any other names, otherwise icons from Next will rewrite your custom icons in Hexo.
favicon:
    #small: /images/favicon-16x16-next.png
    small: /images/Memento.ico
    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

NexT 主題添加多字體

TODO: 首頁 index.html 會出現異常,沒法用 gulp 壓縮

  1. 修改 source/css/_variables/base.styl 文件中的字體獲取方法:
get_font_family(config) {
  custom_family = hexo-config('font.' + config + '.family')
  // 在這裏把引號去除
  return custom_family is a 'string' ? unquote(custom_family) : null
}
  1. 再修改主題配置文件:
global:
    # external: true will load this font family from host.
    external: true
    family: '"Consolas", "Helvetica Neue", Helvetica, Arial'

博文置頂

參考:

  1. hexojs/hexo-generator-index
  2. hexo-generator-index-pin-top
  3. 解決Hexo置頂問題

卸載原裝的 hexo-generator-index, 並安裝 hexo-generator-index-pin-top:

npm uninstall hexo-generator-index --save
npm install hexo-generator-index-pin-top --save

而後在文章中添加 top:

---
title: 2018
date: 2018-10-25 16:10:03
top: 10
---

top 值越大位置越靠前;
設置置頂標記, 定位 /themes/next/layout/_macro/post.swig<div class="post-meta"> 標籤下:

{% if post.top %}
    <i class="fa fa-thumb-tack"></i>
    <font color=7D26CD>置頂</font>
    <span class="post-meta-divider">|</span>
{% endif %}

頂部進度條

參考: theme-next-pace

  1. 將項目中的 css 和 js 文件下載放置到 /themes/next/source/lib/pace/ 目錄下;
  2. 在主題配置文件中啓用:
# Progress bar in the top during page loading.
# Dependencies: https://github.com/theme-next/theme-next-pace
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
pace_theme: pace-theme-minimal

本地搜索

參考: hexo-generator-searchdb

npm install hexo-generator-searchdb --save

在博客配置文件中添加:

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

而後在主題配置文件中啓用本地查詢:

# 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

返回頂部+當前瀏覽進度

next 主題配置文件中啓用:

back2top:
    enable: true
    # Back to top in sidebar.
    sidebar: true
    # Scroll percent label in b2t button.
    scrollpercent: true

右上角/左上角的 Fork me on github

在主題配置文件中啓用:

# Follow me on GitHub banner in right-top corner.
github_banner:
    enable: true
    permalink: https://github.com/Memento1990
    title: Follow me on GitHub

內容分享, AddThis

TODO: Firefox 瀏覽器下失效

評論模塊

  1. valine
  2. gitment
  3. gitalk
  4. gitter
  5. LiveRe(來必應)

數據統計與分析 不蒜子

在主題配置文件中啓用:

# Show Views / Visitors of the website / page with busuanzi.
# Get more information on http://ibruce.info/2015/04/04/busuanzi
busuanzi_count:
    enable: true
    total_visitors: true
    total_visitors_icon: user
    total_views: true
    total_views_icon: eye
    post_views: true
    post_views_icon: eye

2、文章設置

文章末尾結束標記

在路徑 \themes\next\layout\_macro 中新建 passage-end-tag.swig 文件,並添加如下內容:

<div>
    {% if not is_index %}
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文至此結束<i class="fa fa-heartbeat"></i>感謝您的閱讀-------------</div>
    {% endif %}
</div>

接着打開 \themes\next\layout\_macro\post.swig 文件, 在 post-body 以後, post-footer 以前添加代碼(post-footer以前兩個DIV):

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

最後再主題配置文件中啓用:

# 文章末尾添加「本文結束」標記
passage_end_tag:
  enabled: true

複製文本版權信息

文章底部版權信息

參考: hexo-addlink

安裝

npm install hexo-addlink --save

在博客配置文件中進行設置:

addlink:
  before_text: hello # text before the post link
  after_text: bye # text after the post link

增長首頁中顯示"閱讀全文"

在主題配置文件中啓用:

# Automatically Excerpt. Not recommend.
# Use <!-- more --> in the post to control excerpt accurately.
auto_excerpt:
    enable: true
    length: 150

3、優化設置

修改字體加載源

修改主題配置文件:

font:
    enable: true
    # Uri of fonts host, e.g. //fonts.googleapis.com (Default).
    host: //fonts.lug.ustc.edu.cn # 中科大
    # //fonts.geekzu.org # 極客族
    # //fonts.css.network # 捷速網絡 香港

博文壓縮

安裝 gulp 相關包:

npm install gulp -g
npm install gulp-minify-css gulp-uglify gulp-htmlmin gulp-htmlclean gulp-imagemin 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');
var imagemin = require('gulp-imagemin');
var del = require('del');
var Hexo = require('hexo');

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

// 利用Hexo API 來生成博客內容, 效果和在命令行運行: hexo g 同樣
// generate html with 'hexo generate'
var hexo = new Hexo(process.cwd(), {});
gulp.task('generate', function (cb) {
    hexo.init().then(function () {
        return hexo.call('generate', {
            watch: false
        });
    }).then(function () {
        return hexo.exit();
    }).then(function () {
        return cb()
    }).catch(function (err) {
        console.log(err);
        hexo.exit(err);
        return cb(err);
    })
})

// 壓縮 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,
        }).on('error', function(e){
            console.log(e);
        }))
        .pipe(gulp.dest('./public'))
});

// 壓縮 public/js 目錄 js
gulp.task('minify-js', function () {
    return gulp.src('./public/**/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('./public'));
});

// 壓縮public目錄下的全部img: 這個採用默認配置
gulp.task('minify-img', function () {
    return gulp.src('./public/images/**/*.*')
        .pipe(imagemin())
        .pipe(gulp.dest('./public/images'))
})

// 同上,壓縮圖片,這裏採用了: 最大化壓縮效果。
gulp.task('minify-img-aggressive', function () {
    return gulp.src('./public/images/**/*.*')
        .pipe(imagemin(
            [imagemin.gifsicle({ 'optimizationLevel': 3 }),
            imagemin.jpegtran({ 'progressive': true }),
            imagemin.optipng({ 'optimizationLevel': 7 }),
            imagemin.svgo()],
            { 'verbose': true }))
        .pipe(gulp.dest('./public/images'))
})

// 執行順序: 清除public目錄 → 產生原始博客內容 → 執行壓縮混淆
gulp.task('build', gulp.series('clean', 'generate',
    gulp.parallel('minify-html', 'minify-css', 'minify-js', 'minify-img-aggressive')), function (cb) {
    });

gulp.task('default', gulp.series(['build']))

而後每次執行 gulp 命令後就會自動執行 clean, generate, [同步執行相關壓縮方法]...

4、其餘設置

文章開頭 Front-matter

參數 描述 默認值
layout 佈局
title 標題
date 創建日期 文件創建日期
updated 更新日期 文件更新日期
comments 開啓文章的評論功能 true
tags 標籤(不適用於分頁)
categories 分類(不適用於分頁)
permalink 覆蓋文章網址

References

  1. hexo 官網
  2. NexT 主題
  3. NexT 主題官網
  4. hexo的next主題個性化教程:打造炫酷網站
  5. 【持續更新】最全Hexo博客搭建+主題優化+插件配置+經常使用操做+錯誤分析
  6. Hexo Next 博客自定義配置
  7. 打造個性超讚博客Hexo+NexT+GitHubPages的超深度優化
  8. NexT 主題優化
  9. 主題配置
相關文章
相關標籤/搜索