扫一扫分享
unified是一个通过使用语法树来进行解析、检查、转换和序列化文本内容的接口,可以处理Markdown、html和自然语言。它是一个库,作为一个独立的执行接口,负责执行器的角色,调用其生态上相关的插件完成具体任务。同时unified也代表一个生态,要完成前面说的文本处理任务需要配合其生态下的各种插件,截止到目前,它生态中的插件已经有三百多个!鉴于数量实在太多,很容易迷失在它庞大的生态里,可谓是劝退生态。
unified主要有四个生态:remark、rehype、retext、redot,这四个生态下又有各自的生态,此外还包括处理语法树的一些工具、其他构建相关的工具。
unified的执行流程说出来我们应该都比较熟悉,分为三个阶段:
1.Parse
将输入解析成语法树,mdast负责定义规范,remark和rehype等处理器否则创建。
2.Transform
上一步生成的语法树会被传递给各种插件,进行修改、检查、转换等工作。
3.Stringify
这一步会将处理后的语法树再重新生成文本内容。
unified的独特之处在于允许一个处理流程中进行不同格式之间的转换,所以能满足我们本文的需求,也就是将Markdown语法转换成HTML语法,我们会用到其生态中的remark(解析Markdown)、rehype(解析HTml)。
npm安装
npm install unified
使用示例
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import rehypeDocument from 'rehype-document'
import rehypeFormat from 'rehype-format'
import rehypeStringify from 'rehype-stringify'
import {reporter} from 'vfile-reporter'
unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeDocument, {title: 'tit'})
.use(rehypeFormat)
.use(rehypeStringify)
.process('# Hello world!')
.then(
(file) => {
console.error(reporter(file))
console.log(String(file))
},
(error) => {
// Handle your error here!
throw error
}
)
产出:
no issues found
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>tit</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
手机预览