最近有人問我博客的代碼塊是怎麼做的,如下面的代碼塊,然後好久沒有寫文章了,趁着週末有時間就水一篇吧~
var arr = 'abcdaabc'; var info = arr .split('') .reduce((p, k) => (p[k]++ || (p[k] = 1), p), {}); console.log(info); //{ a: 3, b: 2, c: 2, d: 1 }
hexo
會有各種生命週期和事件,平時可能不會用到,但是能很好的利用的話,可以提高不少效率。比如文章多到一定程度之後,每次創建新文章都會被淹沒在文件夾裏面,在博客根目錄下創建一個 scripts
文件夾,放一個 events.js
文件。這樣每次通過hexo new post
創建新文章就會自動用 code
打開了~
var exec = require('child_process').exec; // new 後自動打開編輯器 hexo.on('new', function (data) { console.log('code ' + data.path); exec('code ' + data.path); });
又或者是在 hexo deploy
之後想做一些事情的時候也可以用到
try { hexo.on('deployAfter', function () { //當deploy完成後執行備份 doSomething(); }); } catch (e) { console.log("產生了一個錯誤<( ̄3 ̄)> !,錯誤詳情爲:" + e.toString()); }
代碼塊也是利用了 hexo
的 api
,是在主題目錄下面的 scripts
文件夾,我創建了一個 codeblock.js
文件。監聽 after_post_render
事件,(這個事件並不是每次都觸發,hexo
會做緩存,在沒有緩存的情況下才會執行。)通過事件回調替換文章渲染出來的內容。
var attributes = [ 'autocomplete="off"', 'autocorrect="off"', 'autocapitalize="off"', 'spellcheck="false"', 'contenteditable="true"' ] var attributesStr = attributes.join(' ') hexo.extend.filter.register('after_post_render', function (data) { while (/<figure class="highlight ([a-zA-Z]+)">.*?<\/figure>/.test(data.content)) { data.content = data.content.replace(/<figure class="highlight ([a-zA-Z]+)">.*?<\/figure>/, function () { var language = RegExp.$1 || 'plain' var lastMatch = RegExp.lastMatch lastMatch = lastMatch.replace(/<figure class="highlight /, '<figure class="iseeu highlight /') return '<div class="highlight-wrap"' + attributesStr + 'data-rel="' + language.toUpperCase() + '">' + lastMatch + '</div>' }) } return data })
然後在 highlight.js
的基礎上調整下樣式,包裹上一層類 mac Panel
的效果。
在 blog/themes/next/source/css/_custom
目錄下新建一個 .styl
的樣式文件 ,文件內容如下
.highlight-wrap[data-rel] { position: relative; overflow: hidden; border-radius: 5px; box-shadow: 0 10px 30px 0px rgba(0, 0, 0, 0.4); margin: 35px 0; ::-webkit-scrollbar { height: 10px; } ::-webkit-scrollbar-track { -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); border-radius: 10px; } ::-webkit-scrollbar-thumb { border-radius: 10px; -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5); } &::before { color: white; content: attr(data-rel); height: 38px; line-height: 38px; background: #21252b; color: #fff; font-size: 16px; position: absolute; top: 0; left: 0; width: 100%; font-family: 'Source Sans Pro', sans-serif; font-weight: bold; padding: 0px 80px; text-indent: 15px; float: left; } &::after { content: ' '; position: absolute; -webkit-border-radius: 50%; border-radius: 50%; background: #fc625d; width: 12px; height: 12px; top: 0; left: 20px; margin-top: 13px; -webkit-box-shadow: 20px 0px #fdbc40, 40px 0px #35cd4b; box-shadow: 20px 0px #fdbc40, 40px 0px #35cd4b; z-index: 3; } }
然後在同目錄 custom.styl
文件中引入新建的樣式文件即可
最後修改主題的代碼樣式配置文件
highlight_theme: night eighties
OK,大功告成~