icon

nazo6.dev

一覧に戻る
2023/7/3 2023/7/4 1 min read

プレーンなmarkdownをmdxに変換

目次


プレーンなmarkdownをmdxに変換


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));
}

#参考

Share this article:
一覧に戻る

© 2025 nazo6. All rights reserved.