本项目是用于简化解析markdown过程,并提供各种自定义插件增强解析特征,对外发布时将会使封装成链式操作给使用者。
由于unified使用的是纯ESM,dumi在引入unified
时需要动态引入,因为CommonJS
代码需要引用ESM
包需要用dynamic import
语法,不能直接import
。我们希望将本项目其封装成为CommonJS,屏蔽掉直接使用时的动态引入(见下图),以供umi项目方便直接导入使用。
封装调用链
代码比较简单,仅仅是封装了一下unified的操作
// /src/core/UnifiedChain.ts
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkStringify from 'remark-stringify';
class UnifiedChain {
processor: ReturnType<typeof unified>
content: string = ''
type: string = ''
constructor() {
this.processor = unified()
}
getProcessor() { return this.processor; }
parseMarkdown(content?: string) {
if(content) this.content = content
this.type = 'markdown'
this.processor.use(remarkParse)
return this
}
use(plugin: any, ...settings: any) {
this.processor.use(plugin, settings)
return this
}
toString() {
if(this.type == 'markdown') {
const res = this.processor.use(remarkStringify)
.processSync(this.content)
return String(res)
}
}
}
export default UnifiedChain
复制代码
创建一个导出函数供外部调用
// /src/index.ts
import UnifiedChain from './core/UnifiedChain';
import remarkFootnote from './remark/remarkFootnote';
export default function unifiedChain() {
return new UnifiedChain()
}
export {
remarkFootnote
}
复制代码
创建调试代码
// /index.js
import unifiedChain, { remarkFootnote } from "./src";
const res = unifiedChain()
.parseMarkdown('# hello chain')
.use(remarkFootnote)
.toString()
console.log(res)
复制代码
改变package.json运行脚本
"dev": "tsx ./index",
复制代码
运行命令正常打印
创建测试代码
// /test/index.test.ts
import unifiedChain, { remarkFootnote } from "../src";
test('index', () => {
const res = unifiedChain()
.parseMarkdown('# hello chain')
.use(remarkFootnote)
.toString()
console.log(res)
});
复制代码
运行命令正常打印