Markdown Implementation: Claude Code 활용 가이드
markdown implementation: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.
Markdown処理をClaude Code로 효율화하기
ブ로그や문서サイトでは、Markdownの解析・変換・확장が必要になります。Claude Code를 활용하면 remarkやrehypeの플러그인개발からカスタム컴포넌트の구현まで短시간で구축할 수 있습니다。
unified/remark에 의한Markdown解析
> remarkでMarkdownを解析してHTML変換する파이프라인を作って。
> コードハイライト、GFM대응、目次생성も含めて。
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 |
`);
目다음自動생성
Markdownの見出しから目次(TOC)を自動생성する機能です。
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: [] });
}
// ネスト構造に変換
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;
}
カスタムremark플러그인
Markdownに独自の構文を추가する플러그인を생성します。
import { visit } from "unist-util-visit";
import type { Plugin } from "unified";
import type { Root, Paragraph, Text } from "mdast";
// :::note や :::warning で囲むと알럿ブロックに変換する플러그인
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に変換
(node as any).type = "html";
(node as any).value = `<div class="alert alert-${type}"><p>${content}</p></div>`;
(node as any).children = undefined;
});
};
};
MarkdownからReact컴포넌트への変換
MDXを使わずにMarkdownをReact컴포넌트に変換する方法です。
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 }}
/>
);
}
Markdown파일のフロントマター解析
ブ로그글などのフロントマターを含む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,
};
}
// 複数파일の一括로딩
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.md파일の書き方에 대해서는CLAUDE.md설정の모범 사례を、Webスクレイピングで취득した데이터の加工はWebスクレイピング를 확인하세요.
정리
Claude Code를 활용하면 Markdownの解析파이프라인구축、カスタム플러그인개발、フロントマター解析、目次생성まで、Markdown処理에 관한구현を短시간で완료할 수 있습니다。「こんなMarkdown확장を作りたい」と伝える만으로적절한구현が得られます。
자세한 내용은Claude Code공식 문서를 참고하세요.
Related Posts
Claude Code 생산성을 3배로 높이는 10가지 팁
Claude Code를 더 효과적으로 활용하는 10가지 실전 팁을 공개합니다. 프롬프트 전략부터 워크플로 단축키까지, 오늘부터 바로 적용해 보세요.
Canvas/WebGL Optimization: Claude Code 활용 가이드
canvas/webgl optimization: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.
Practicing AI Pair Programming: Claude Code 활용 가이드
practice AI pair programming: Claude Code 활용. Includes practical tips and workflows.