我希望在我的Next.js博客中包含PrismJS,以便突出显示.md文件中的代码。使用remark
和remark-html
在/lib/posts.js中处理markdown并将其作为HTML传递给react-markdown
// /lib/posts.js
export async function getPostData(id) {
const fullPath = path.join(postsDirectory, `${id}.md`);
const fileContents = fs.readFileSync(fullPath, "utf8");
const matterResult = matter(fileContents);
const processedContent = await remark()
.use(html)
.process(matterResult.content);
const contentHtml = processedContent.toString();
return {
id,
contentHtml,
...matterResult.data,
};
}
内容Html是在[id].js中获取的,我使用ReactMarkdown进行渲染。在这里,我导入Prism并使用CodeBlock函数进行高亮显示。我在_app.js
中导入prism.css
,放在我的global.css
旁边。
// /pages/_app.js
import Container from "../components/Container";
import "../styles/global.css";
import "../styles/prism.css";
export default ({ Component, pageProps }) => (
<Container>
<Component {...pageProps} />
</Container>
);
// /pages/posts/[id].js
import { getAllPostIds, getPostData } from "../../lib/posts";
import ReactMarkdown from "react-markdown/with-html";
import Prism from "prismjs";
const CodeBlock = (language, values) => {
return <Prism language={language}>{values}</Prism>;
};
export default function Post({ postData }) {
return (
<ReactMarkdown
escapeHtml={false} // Dangerous if content is user-generated
source={postData.contentHtml}
renderers={{ code: CodeBlock }}
/>
);
}
export async function getStaticPaths() {
const paths = getAllPostIds();
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params }) {
const postData = await getPostData(params.id);
return {
props: {
postData,
},
};
}
当我手动输入URL并按回车时,它能正常工作。例如 https://nextjs-blog-ivory-nine.vercel.app/posts/first-next-js-blog-devdiary 但是当我从主页面https://nextjs-blog-ivory-nine.vercel.app导航到第一篇文章时,代码就无法高亮显示。 你有什么想法吗? 提前感谢!