nazo6 notememo

プレーンなmarkdownをmdxに変換

作成:2023/07/03

更新:2023/07/04

markdownのhtmlにclass属性が含まれていたりstyle属性が文字列だったりするとmdxとして読み込めなくなるのでそれを変換する。
import { Plugin, unified } from "unified";
import remarkParse from "remark-parse";
import remarkStringify from "remark-stringify";
import remarkFrontmatter from "remark-frontmatter";
import { visit } from "unist-util-visit";
import { Root } from "mdast";
import * as fs from "fs/promises";
// @ts-ignore
import { default as convert } from "html-to-jsx";

const remarkPlugin: Plugin<[], Root> = () => {
return (tree) => {
visit(tree, (node) => {
console.log(node);
if (node.type == "html") {
const jsx = convert(node.value);
node.value = jsx;
}
});
};
};

main();

async function main() {
const file = await unified()
.use(remarkParse)
.use(remarkPlugin)
.use(remarkStringify, { fences: true })
.use(remarkFrontmatter, ["yaml", "toml"])
.process(
await fs.readFile(
"./home.md",
{ encoding: "utf8" },
),
);

console.log(String(file));
}

参考