為你的VuePress部落格添加GitTalk評論

  • 2019 年 11 月 5 日
  • 筆記

背景

突發奇想,想讓自己的 《前端進階小書》擁有評論功能,於是開始了探索之路

實現之路

1. 創建一個 OAuth Apps

Github 設置中找到 Settings / Developer settings / OAuth Apps / new OAuth Apps, 創建一個應用

創建成功有 Client IDClient Secret ,保存下來,後面我們會用到。

2. 創建評論組件

Vuepress 默認 .vuepress / components 文件夾下的組件會全局註冊, 因此我們創建一個 comment 組件

gittalk.css 請點擊 這裡

<template>    <div class="gitalk-container">      <div id="gitalk-container"></div>    </div>  </template>  <script>  export default {    name: 'comment',    data() {      return {};    },    mounted() {      let body = document.querySelector('.gitalk-container');      let script = document.createElement('script');      script.src = 'https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js';      body.appendChild(script);      script.onload = () => {        const commentConfig = {          clientID: '你的clientID',          clientSecret: '你的clientSecret',          repo: '你的倉庫名稱',          owner: '你的用戶名',          // 這裡接受一個數組,可以添加多個管理員,可以是你自己          admin: ['管理用戶名'],          // id 用於當前頁面的唯一標識,一般來講 pathname 足夠了,          // 但是如果你的 pathname 超過 50 個字元,GitHub 將不會成功創建 issue,此情況可以考慮給每個頁面生成 hash 值的方法.          id: location.pathname,          distractionFreeMode: false,        };        const gitalk = new Gitalk(commentConfig);        gitalk.render('gitalk-container');      };    },  };  </script>  <style>  @import '../css/gittalk.css';  </style>    複製程式碼

3. 使用評論組件

理論上,我們在每個 markdown 文件里直接加入這個組件即可,但是每次都添加有點麻煩,還是讓 node 來幫我們吧

根目錄創建 build 文件夾, 創建三個文件 addComponents.js, delComponents.js, findMarkdown.js, 分別程式碼如下:

// addComponents.js  const fs = require("fs");  const findMarkdown = require("./findMarkdown");  const rootDir = "./docs";    findMarkdown(rootDir, writeComponents);    function writeComponents(dir) {      if (!/README/.test(dir)) {          fs.appendFile(dir, `n n <comment/> n `, err => {              if (err) throw err;              console.log(`add components to ${dir}`);          });      }  }  複製程式碼
// delComponents.js  const fs = require("fs");  const findMarkdown = require("./findMarkdown");  const rootDir = "./docs";    findMarkdown(rootDir, delComponents);    function delComponents(dir) {      fs.readFile(dir, "utf-8", (err, content) => {          if (err) throw err;            fs.writeFile(              dir,              content.replace(/n n <comment/> n /g, ""),              err => {                  if (err) throw err;                  console.log(`del components from ${dir}`);              }          );      });  }  複製程式碼
// findMarkdown.js  const fs = require("fs");    function findMarkdown(dir, callback) {      fs.readdir(dir, function(err, files) {          if (err) throw err;          files.forEach(fileName => {              let innerDir = `${dir}/${fileName}`;              if (fileName.indexOf(".") !== 0) {                  fs.stat(innerDir, function(err, stat) {                      if (stat.isDirectory()) {                          findMarkdown(innerDir, callback);                      } else {                          // 跳過readme 文件,當然你也可以自行修改                          if (/.md$/.test(fileName) && !/README/.test(fileName))                              callback(innerDir);                      }                  });              }          });      });  }  module.exports = findMarkdown;  複製程式碼

修改 package.jsonscripts, 先為每個 md 文件添加組件,然後打包,最後再一一刪除 markdown 中的 comment 組件

"build": "node ./builds/addComponents.js && vuepress build docs && node ./builds/delComponents.js",

OK,大功告成,將你的項目推上 github 試試看吧

效果可以看我的項目 《前端進階小書》 查看。 That is all!