Newer
Older
hello-programmer-world / src / plugins / remarkCodeFile.ts
import fs from "node:fs";
import path from "node:path";
import { visit } from "unist-util-visit";

export default function remarkCodeFile() {
  return (tree: any, file: any) => {
    visit(tree, "code", (node) => {
      if (!node.meta) return;

      const match = node.meta.match(/file=(.+)/);
      if (!match) return;

      const relativePath = match[1].trim();
      const fullPath = path.resolve(process.cwd(), relativePath);

      if (!fs.existsSync(fullPath)) {
        throw new Error(`Code file not found: ${relativePath}`);
      }

      node.value = fs.readFileSync(fullPath, "utf8");
      node.meta = undefined; // meta は消しておく(任意)
    });
  };
}