hexo使用grunt實現自動化 | hexo

本文介紹hexo使用grunt實現一些自動化操作。

開發過前端或者node.js的同學對grunt應該不陌生,如果對grunt不熟悉可略過本文。

開始使用hexo來處理靜態博客時我就遇到了問題,我的文章已經寫了很多篇了,都是markdown格式,而且託管在github上了,然而hexo並不支持導入文章。

好在我發現只要把markdown文件拷貝到hexo裏的source/_posts,hexo就會解析,我可以考慮直接把所有文章直接拷貝到這個目錄。

但是另外一個問題又出現了,問題在於存在兩份一模一樣的源文件,一份我託管在github上,一份在source/_posts,後期文章改動的話,兩邊不同步,維護很費力。

後來想到的方法就是利用自動化工具來處理源文件的拷貝,博客的部署等一些操作。由於對grunt比較熟悉,所以使用了grunt。

如果對grunt不熟悉,可以前往grunt 網站

準備

  • 切換到hexo博客目錄
  • 執行以下命令安裝grunt cli: npm install -g grunt-cli
  • 執行以下命令安裝grunt: npm install grunt --save-dev
  • 執行以下命令安裝插件:npm install --save-dev grunt-bg-shell grunt-contrib-clean grunt-contrib-copy grunt-contrib-watch grunt-rewrite grunt-zip grunt-shell load-grunt-tasks
  • 新建Gruntfile.js
  • 新建raw目錄

完成後,我的hexo博客裏的目錄結構是這樣子的:
image

grunt插件說明

以下爲使用到的插件:

插件 作用
grunt-bg-shell 在後臺運行shell命令
grunt-contrib-clean 刪除文件和目錄
grunt-contrib-copy 拷貝文件和目錄
grunt-contrib-watch 監測文件的新增、修改與刪除並運行對應的任務
grunt-rewrite 文件特定內容的替換
grunt-shell 運行shell命令
grunt-zip zip壓縮
load-grunt-tasks 自動加載grunt插件

Gruntfile.js 編寫

新建Gruntfile.js,以下是我的Gruntfile.js的內容:

// see: https://gruntjs.com/sample-gruntfile
module.exports = function(grunt) {

  var config = {
    pkg: grunt.file.readJSON('package.json'),
    pathConfig: {
      raw: 'raw',
      posts: 'source/_posts',
    },

    clean: {
      posts: {
        src: ['<%= pathConfig.posts %>/'],
      },
    },

    copy: {
      main: {
        files: [{
          expand: true,
          cwd: '<%= pathConfig.raw %>',
          src: '**/*.md',
          dest: '<%= pathConfig.posts %>',
          flatten: true,
          filter: function(filepath) {
            // var patterns = ['---\ntitle:'];
            var patterns = ['^---$'];
            var matchRegex = function(filepath, patterns) {
              var content = grunt.file.read(filepath);

              return patterns.some(function(pattern){
                var regex = new RegExp(pattern, 'm');
                // var regex = new RegExp(pattern);
                return regex.test(content);
              });
            };
            return matchRegex(filepath, patterns);
          },
        }],
      },
    },

    watch: {
      raw: {
        files: ['<%= pathConfig.raw %>/**/*.md'],
        tasks: ['copy:main'],
        options: {
          // spawn: false,
        },
      },
    },

    bgShell: {
      hexoServer: {
        cmd: 'hexo server',
        bg: true,
      },

    },

    shell: {
      gitClone: {
        command: 'git clone [email protected]:xxxxxxx/my_blog.git <%= pathConfig.raw %>/my_blog'
      },
      gitPullRaw: {
        command: 'cd ./raw/my_blog && git pull'
      },

      hexoGenerate: {
        command: 'hexo g',
      },
      hexoClean: {
        command: 'hexo clean',
      },
    },

    rewrite: {
      abbrlink: {
        src: '<%= pathConfig.raw %>/**/*.md',
        editor: function(contents, filepath){
          const crypto = require('crypto');
          const hash = crypto.createHash('sha256');

          hash.update(contents);
          var hashValue = hash.digest('hex');

          return contents.replace(/abbrlink: 3fb9c7a4f247726d/g, "abbrlink: " + hashValue.substring(0, 16));
        }
      },
    },

    zip: {
      dist: {
        src: [
          'public/**/*',
        ],
        dest: 'blog.zip'
      }
    }

  };

  grunt.initConfig(config);
  require('load-grunt-tasks')(grunt);

  // 運行grunt init 調用此任務
  grunt.registerTask('init', [
    'shell:gitClone'
  ]);

  grunt.registerTask('RawToPosts', [
    'shell:gitPullRaw',
    'rewrite:abbrlink',
    'copy:main',
  ]);

  // 運行 grunt 或者 grunt default 調用此任務
  grunt.registerTask('default', [
    'clean:posts',
    'RawToPosts',
    'bgShell:hexoServer',
    'watch',
  ]);

  // 運行grunt build調用此任務
  grunt.registerTask('build', [
    'clean:posts',
    'RawToPosts',
    'shell:hexoClean',
    'shell:hexoGenerate',
    'zip:dist'
  ]);

};

上述Gruntfile.js中有三個比較重要的任務:
* grunt init
* grunt
* grunt build

grunt init 任務是調用shell:gitClone 把我的博客源文件從github上拉取下來,放到raw/my_blog目錄,這個命令只需要執行一次,後期不再需要。

grunt 任務用於日常本地寫博客,它的子任務分別是:
* clean:posts: 刪除source/_posts下的所有文件
* RawToPosts: 從github拉取更新到raw/my_blog,並拷貝符合條件的文件到source/_posts
* bgShell:hexoServer: 執行hexo server,啓動hexo本地服務
* watch: 監測文件變化,輔助hexo server刷新

grunt build 任務用於發佈博客,它的子任務分別是:
* clean:posts: 刪除source/_posts下的所有文件
* RawToPosts: 從github拉取更新到raw/my_blog,並拷貝符合條件的文件到source/_posts
* shell:hexoClean: 執行hexo clean
* shell:hexoGenerate: 執行hexo genetate
* zip:dist: 打包public成爲blog.zip

通過上述grunt自動化腳本,我保持了博客文件與hexo博客環境相分離的目標,我只需要運行grunt build,grunt會自動幫我拉取最新的博客文件並最終生成hexo目標文件。

這樣做的好處是以後不使用hexo時,我可以很方便轉移我的博客。

其他

如果是使用github pages來託管博客的同學,可以把grunt buildzip:dist換成自動部署博客的任務,就能一鍵部署啦。

更多

更多內容參考:hexo博客搭建彙總

發佈了38 篇原創文章 · 獲贊 10 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章