前言
最近 varlet
新出了一个工具库 github.com/varletjs/ra…,站点是通过 vitepress
搭建的。众所周知,写这些代码可能花不了多久,写文档往往都要花上很久,公司也有些这方面的需求,所以就考虑自己做个工具来实现这个需求。于是,花了一下午的时间,我做了这个工具。应用到 vitepress
里,可以快速构建工具函数站点。
思路
- 分离出文件的jsdoc注释和函数代码
- 解析jsdoc,这里用了一个 库
- 生成markdown文件的内容
特性
- 源代码很精简,仅 100 多行
- 工具库的产物支持 ESM 和 CJS
- 生成的 markdown 内容高度可拓展
- 可借助 gulp 或者 js脚本 实现批量处理文件
效果
js file
ts file
使用
可以通过js脚本读文件,转化,生成md文件。
import fs from 'fs'
import { fileURLToPath } from 'url'
import { jsdocToMD } from '@binbinji/jsdoctomd'
function generateMD() {
const examplePath = fileURLToPath(new URL('../example', import.meta.url))
const docsPath = fileURLToPath(new URL('../docs', import.meta.url))
const exampleFiles = fs.readdirSync(examplePath)
exampleFiles.forEach((file) => {
const [fileName, extname] = file.split('.')
const input = fs.readFileSync(`${examplePath}/${file}`, 'utf-8')
const output = jsdocToMD({ input, extname })
if (!fs.existsSync(docsPath)) {
fs.mkdirSync(docsPath)
}
fs.writeFileSync(`${docsPath}/${fileName}.md`, output)
})
}
generateMD()
也可以使用 gulp 来自动化工作流。
// gulpfile.js
import { src, dest } from 'gulp'
import rename from 'gulp-rename'
import { Transform } from 'stream'
import { jsdocToMD } from '@binbinji/jsdoctomd'
function generateMDFiles() {
return src('example/*.{ts,js}') // the files will be converted to md
.pipe(
new Transform({
objectMode: true,
transform(file, _enc, cb) {
const extname = file.extname.slice(1)
const output = jsdocToMD({ input: file.contents.toString(), extname })
file.contents = Buffer.from(output)
cb(null, file)
},
}),
)
.pipe(rename({ extname: '.md' }))
.pipe(dest('docs')) // the output dir
}
export default generateMDFiles