跳至主要内容

[note] Unified remarkJS 筆記

remarkjs

remarkjs 是透過 unified 的流程來處理 markdown 的檔案,它透過 unified API 提供的流程,透過 remark-parse 將 markdown 檔案解析成 markdown syntax tree (mdast),接著可以使用 unified 的 plugin 來對該 markdown 進行操作,最後則透過 remark-stringify 來輸出成修改後的 markdown。

remark-parse

注意

unifiedremark-parseremark-stringify 自 unified v10 / remark v14 起已改為 ESM-only(僅支援 ES Module),不再支援 require() 的 CommonJS 用法。下方範例使用的是舊版 CommonJS 寫法,現代用法請改用 import 語法。

// 取得 markdown tree
const unified = require('unified');
const markdown = require('remark-parse');

const tree = unified()
.use(markdown) // parser
.parse('# Hello world!');
// parser -> compile -> 寫檔
const markdown = require('remark-parse');
const stringify = require('remark-stringify');

const tree = unified()
.use(markdown) // parser
.use(stringify) // compiler
.process(vfile.readSync('blog.md'), function (err, file) {
console.error(report(err || file));
if (file) {
file.extname = '.txt';
vfile.writeSync(file); // Written to `index.html`.
}
});