Tips & Tricks

Markdown Implementation dengan Claude Code

Pelajari tentang markdown implementation menggunakan Claude Code. Dilengkapi tips praktis dan contoh kode.

Markdownpemrosesan dengan Claude Code: efisiensi

ブログやdokumenサイト 、Markdown 解析・konversi・拡張 diperlukan なり.Claude Code 使えば、remarkやrehype pluginpengembangan dari カスタムkomponen implementasiま waktu singkat pembangunan bisa dilakukan.

unified/remarkによるMarkdown解析

> remark dengan Markdown 解析してHTMLkonversiするpipeline buatkan.
> コードハイライト、GFMdukungan、目次generate juga 含めて。
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkGfm from "remark-gfm";
import remarkRehype from "remark-rehype";
import rehypeHighlight from "rehype-highlight";
import rehypeStringify from "rehype-stringify";
import rehypeSlug from "rehype-slug";

export async function markdownToHtml(markdown: string): Promise<string> {
  const result = await unified()
    .use(remarkParse)
    .use(remarkGfm) // テーブル、チェックリスト、取り消し線
    .use(remarkRehype, { allowDangerousHtml: true })
    .use(rehypeSlug) // 見出し ID 付与
    .use(rehypeHighlight) // コードハイライト
    .use(rehypeStringify, { allowDangerousHtml: true })
    .process(markdown);

  return String(result);
}

// Usage example
const html = await markdownToHtml(`
# はじめに

これは**テスト**です。

## コード例

\`\`\`typescript
const greeting = "Hello, World!";
console.log(greeting);
\`\`\`

| 項目 | 値 |
|------|-----|
| A    | 100 |
| B    | 200 |
`);

自動generate 目次

Markdown 見出し dari 目次(TOC) 自動generate 機能.

interface TocItem {
  id: string;
  text: string;
  level: number;
  children: TocItem[];
}

export function extractToc(markdown: string): TocItem[] {
  const headingRegex = /^(#{1,6})\s+(.+)$/gm;
  const items: TocItem[] = [];
  let match: RegExpExecArray | null;

  while ((match = headingRegex.exec(markdown)) !== null) {
    const level = match[1].length;
    const text = match[2].trim();
    const id = text
      .toLowerCase()
      .replace(/[^\w\s\u3000-\u9fff]/g, "")
      .replace(/\s+/g, "-");

    items.push({ id, text, level, children: [] });
  }

  // ネストstruktur konversi
  const toc: TocItem[] = [];
  const stack: TocItem[] = [];

  items.forEach((item) => {
    while (stack.length > 0 && stack[stack.length - 1].level >= item.level) {
      stack.pop();
    }

    if (stack.length === 0) {
      toc.push(item);
    } else {
      stack[stack.length - 1].children.push(item);
    }

    stack.push(item);
  });

  return toc;
}

カスタムremarkplugin

Markdown 独自 構文 penambahan plugin pembuatan.

import { visit } from "unist-util-visit";
import type { Plugin } from "unified";
import type { Root, Paragraph, Text } from "mdast";

// :::note や :::warning 囲む dan アラートブロック konversiplugin
export const remarkAlert: Plugin<[], Root> = () => {
  return (tree) => {
    visit(tree, "paragraph", (node: Paragraph, index, parent) => {
      const firstChild = node.children[0];
      if (firstChild?.type !== "text") return;

      const text = (firstChild as Text).value;
      const match = text.match(/^:::(note|warning|tip|danger)\s*\n/);

      if (!match) return;

      const type = match[1];
      const content = text.slice(match[0].length).replace(/\n:::$/, "");

      // カスタムHTML konversi
      (node as any).type = "html";
      (node as any).value = `<div class="alert alert-${type}"><p>${content}</p></div>`;
      (node as any).children = undefined;
    });
  };
};

konversi MarkdownからReactkomponenへ

MDX 使わず Markdown Reactkomponen konversi metode.

import { useMemo } from "react";
import { markdownToHtml } from "./markdown";
import DOMPurify from "isomorphic-dompurify";

interface MarkdownRendererProps {
  content: string;
  className?: string;
}

export function MarkdownRenderer({ content, className }: MarkdownRendererProps) {
  const [html, setHtml] = useState("");

  useEffect(() => {
    markdownToHtml(content).then((result) => {
      setHtml(DOMPurify.sanitize(result));
    });
  }, [content]);

  return (
    <div
      className={`prose prose-lg max-w-none ${className || ""}`}
      dangerouslySetInnerHTML={{ __html: html }}
    />
  );
}

フロントマター解析 Markdownfile

ブログartikel dll. フロントマター 含むMarkdown 解析.

import matter from "gray-matter";

interface BlogPost {
  title: string;
  description: string;
  pubDate: string;
  category: string;
  tags: string[];
  content: string;
}

export function parseBlogPost(fileContent: string): BlogPost {
  const { data, content } = matter(fileContent);

  return {
    title: data.title || "",
    description: data.description || "",
    pubDate: data.pubDate || "",
    category: data.category || "",
    tags: data.tags || [],
    content,
  };
}

// 複数file 一括loading
import fs from "fs/promises";
import path from "path";

export async function getAllPosts(dir: string): Promise<BlogPost[]> {
  const files = await fs.readdir(dir);
  const mdFiles = files.filter((f) => f.endsWith(".md") || f.endsWith(".mdx"));

  const posts = await Promise.all(
    mdFiles.map(async (file) => {
      const content = await fs.readFile(path.join(dir, file), "utf-8");
      return { ...parseBlogPost(content), slug: file.replace(/\.mdx?$/, "") };
    })
  );

  return posts.sort(
    (a, b) => new Date(b.pubDate).getTime() - new Date(a.pubDate).getTime()
  );
}

CLAUDE.mdfile 書き方 mengenai CLAUDE.mdpengaturan best practices 、Webスクレイピング pengambilan データ 加工 Webスクレイピング silakan lihat.

Summary

Dengan Claude Code, Markdown 解析pipelinepembangunan、カスタムpluginpengembangan、フロントマター解析、目次generateま 、Markdownpemrosesan 関 implementasi waktu singkat selesai bisa dilakukan.「こんなMarkdown拡張 作りたい」 dan 伝えるだけ tepatなimplementasi 得られ.

Untuk detail lebih lanjut, lihat Dokumentasi Resmi Claude Code.

#Claude Code #Markdown #remark #rehype #kontenmanajemen