突发奇想,想让本身的 《前端进阶小书》拥有评论功能,因而开始了探索之路javascript
在 Github 设置中找到 Settings / Developer settings / OAuth Apps / new OAuth Apps
, 建立一个应用css
建立成功有 Client ID 和 Client Secret ,保存下来,后面咱们会用到。html
Vuepress 默认 .vuepress / components
文件夹下的组件会全局注册, 所以咱们建立一个 comment 组件前端
gittalk.css 请点击 这里vue
<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>
复制代码
理论上,咱们在每一个 markdown 文件里直接加入这个组件便可,可是每次都添加有点麻烦,仍是让 node 来帮咱们吧java
根目录建立 build 文件夹, 建立三个文件 addComponents.js, delComponents.js, findMarkdown.js
, 分别代码以下:node
// 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.json
的 scripts, 先为每一个 md 文件添加组件,而后打包,最后再一一删除 markdown 中的 comment 组件webpack
"build": "node ./builds/addComponents.js && vuepress build docs && node ./builds/delComponents.js",
复制代码
OK,大功告成,将你的项目推上 github 试试看吧git
效果能够看个人项目 《前端进阶小书》 查看。 That is all!github
Canvas 进阶(二)写一个生成带logo的二维码npm插件
Canvas 进阶(三)ts + canvas 重写”辨色“小游戏