-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathMdxCompiler.ts
More file actions
60 lines (52 loc) · 1.86 KB
/
Copy pathMdxCompiler.ts
File metadata and controls
60 lines (52 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { Node } from "unist";
import { VFileOptions } from "vfile";
// @ts-ignore
import { createCompiler } from "@mdx-js/mdx";
// @ts-ignore
import withSmartQuotes from "@silvenon/remark-smartypants";
import { withTitleCaseHeadings } from "./mdxCompiler/remark/withTitleCaseHeadings";
import { withImages, unwrapImages } from "./mdxCompiler/remark/withImages";
import { withTableOfContents } from "./mdxCompiler/remark/withTableOfContents";
import { withSyntaxHighlighting } from "./mdxCompiler/remark/withSyntaxHighlighting";
import { removeExports } from "./mdxCompiler/remark/removeExports";
const DEFAULT_RENDERER = `
import React from 'react'
import { mdx } from '@mdx-js/react'
`;
type RemarkPlugin = (...args: any[]) => any;
export class MdxCompiler {
private compiler: any;
private readonly remarkPlugins: RemarkPlugin[];
constructor(remarkPlugins: RemarkPlugin[] = []) {
this.remarkPlugins = [
// TODO: fix MDX strings within JSX elements (add a new plugin)
withTitleCaseHeadings,
withTableOfContents,
withImages,
withSyntaxHighlighting,
withSmartQuotes,
unwrapImages,
removeExports,
...remarkPlugins
];
}
async compile(file: any) {
const compiler = this.getCompiler();
const { contents } = await compiler.process(file);
return [
`/* @jsxRuntime classic */`,
`/* @jsx mdx */`,
DEFAULT_RENDERER,
contents.replace(/export const (.*?) \/\* remove \*\/ =/g, "const $1 ="),
`MDXContent.layoutProps = layoutProps;`
].join("\n");
}
private getCompiler() {
if (!this.compiler) {
this.compiler = createCompiler({
remarkPlugins: this.remarkPlugins
});
}
return this.compiler;
}
}