import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { remark } from 'remark';
import html from 'remark-html';
import rehypeParse from 'rehype-parse';
import rehypeStringify from 'rehype-stringify';
import { unified } from 'unified';
import { visit } from 'unist-util-visit';
import remarkPrism from 'remark-prism'; // For syntax highlighting
function rehypeWrapPreBlocks() {
return (tree) => {
visit(tree, 'element', (node, index, parent) => {
if (node.tagName === 'pre') {
const wrapperNode = {
type: 'element',
tagName: 'div',
properties: { className: ['code-block-wrapper'] },
children: [node],
};
parent.children[index] = wrapperNode;
}
});
};
}
const postsDirectory = path.join(process.cwd(), '/src/app/content/pages');
export async function getPageContent(id) {
const fullPath = path.join(postsDirectory, `${id}.md`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
const matterResult = matter(fileContents);
const processedContent = await unified()
.use(remark)
.use(remarkPrism)
.use(html)
.use(rehypeParse, { fragment: true })
.use(rehypeWrapPreBlocks)
.use(rehypeStringify)
.process(matterResult.content);
const contentHtml = processedContent.toString();
return {
id,
contentHtml,
...matterResult.data,
};
}
< /code>
Это вызывается через этот API < /p>
import { NextResponse } from 'next/server';
import { getPageContent } from '@/app/lib/markdown';
export async function GET(request, context) {
const { params } = context;
const slug = params.slug.toLowerCase();
try {
const content = await getPageContent(slug);
return NextResponse.json({
content,
});
} catch (err) {
return NextResponse.json({
error: `${err}`,
});
}
}
< /code>
и его возвращение ошибки
{"error":"TypeError: attacher.call is not a function"}
Код работал интенсивно нормально, но мне пришлось изменить то, как он анализирует отметку, чтобы обернуть такие элементы, как в Div, который я мог бы добавить определенное имя класса. Я закончил этим, и это сломалось. Обычно очевидно, что я просто упустил из виду, поэтому, если у меня есть, пожалуйста, дайте мне знать. По Спасибо!
У меня есть функция, вызываемая в динамическом маршруте, чтобы извлечь уценку из файла .md, проанализировать его и отобразить как содержимое HTML. [code]import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; import { remark } from 'remark'; import html from 'remark-html'; import rehypeParse from 'rehype-parse'; import rehypeStringify from 'rehype-stringify'; import { unified } from 'unified'; import { visit } from 'unist-util-visit'; import remarkPrism from 'remark-prism'; // For syntax highlighting
try { const content = await getPageContent(slug); return NextResponse.json({ content, }); } catch (err) { return NextResponse.json({ error: `${err}`, }); } } < /code> и его возвращение ошибки {"error":"TypeError: attacher.call is not a function"}[/code] Код работал интенсивно нормально, но мне пришлось изменить то, как он анализирует отметку, чтобы обернуть такие элементы, как в Div, который я мог бы добавить определенное имя класса. Я закончил этим, и это сломалось. Обычно очевидно, что я просто упустил из виду, поэтому, если у меня есть, пожалуйста, дайте мне знать. По Спасибо!