-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
66 lines (57 loc) · 1.78 KB
/
index.js
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
61
62
63
64
65
66
var unified = require("unified");
var parse = require("rehype-parse");
var rehype2remark = require("rehype-remark");
var stringify = require("remark-stringify");
var mdx = require("@mdx-js/mdx");
const babel = require(`@babel/core`);
const BabelPluginPluckImports = require(`babel-plugin-pluck-imports`);
const objRestSpread = require(`@babel/plugin-proposal-object-rest-spread`);
const htmlAttrToJSXAttr = require(`./babel-plugin-html-attr-to-jsx-attr`);
const removeExportKeywords = require(`babel-plugin-remove-export-keywords`);
module.exports = async (htmlInput, handlers) => {
const processor = unified()
.use(parse)
.use(rehype2remark, { handlers: { ...handlers } })
.use(stringify);
// const markdown = processor.processSync(htmlInput);
let compiledMarkdown;
//if not a valid markdown, we send empty div to convert into markdown
try {
const markdown = processor.processSync(htmlInput);
compiledMarkdown = await mdx(markdown);
} catch (error) {
compiledMarkdown = await mdx(`<div></div>`);
}
const instance = new BabelPluginPluckImports();
const result = babel.transform(compiledMarkdown, {
configFile: false,
plugins: [
instance.plugin,
objRestSpread,
htmlAttrToJSXAttr,
removeExportKeywords,
],
presets: [
require(`@babel/preset-react`),
[
require(`@babel/preset-env`),
{
useBuiltIns: `entry`,
corejs: 2,
modules: false,
},
],
],
});
// TODO: be more sophisticated about these replacements
body = result.code
.replace(
/export\s*default\s*function\s*MDXContent\s*/,
`return function MDXContent`
)
.replace(
/export\s*{\s*MDXContent\s+as\s+default\s*};?/,
`return MDXContent;`
);
return body;
};