I'm currently working on a blog that includes math formulas in markdown pages. The markdown files are stored locally in a folder. Here is the code snippet from my Blogpage.tsx file-
import React from 'react'
import fs from "fs"
import Markdown from "react-markdown"
import rehypeKatex from "rehype-katex"
import remarkMath from "remark-math"
import rehypeRaw from "rehype-raw"
import matter from "gray-matter"
import 'katex/dist/katex.min.css'
// export const runtime = 'edge'
const getPostContent = (postID: string) => {
const folder = "src/blogPosts";
const file = `${folder}/${postID}.md`;
const content = fs.readFileSync(file, "utf8");
const matterResult = matter(content);
return matterResult;
};
export const generateStaticParams = async () => {
return [{ postID: "blog-post1" }]
};
const BlogPage = (props: any) => {
const postID = props.params.postID;
const post = getPostContent(postID)
return (
<>
<h1>{post.data.title}</h1>
<Markdown remarkPlugins={[remarkMath]} rehypePlugins={[rehypeKatex, rehypeRaw]}>
{post.content}
</Markdown>
</>
)
}
export default BlogPage
Localhost runs smoothly, but encountering an error when trying to deploy on Cloudflare pages.
19:18:58.294 ⚡️ Completed `npx vercel build`.
19:18:58.342 ⚡️ Invalid prerender config for /allblogs/[postID]
...
(remaining log messages)
...
Introducing export const runtime = 'edge'
on the page leads to an error related to the 'fs' module:
Error: Module not found: Can't resolve 'fs'
Looks like there's a conflict between the edge runtime and the nodejs module. Trying an alternate approach using fetch
:
const getPostContent = async (postID: string) => {
const resource = await import(`${folder}/${postID}.md`);
const res = await fetch(resource.default);
if (!res.ok) {
throw new Error(`${resource.default}: ${res.status} ${res.statusText}`);
}
return res.text();
};
This method throws an error -
⨯ unhandledRejection: Error: Cannot find module
Seeking assistance with reading markdown files without utilizing 'fs'. Also looking for alternative ways to import markdown files without conflicting with the edge runtime.
Update
Solved issues with uploading to Cloudflare pages by utilizing NextJS static export feature.
Note: For NextJS version 13 or newer, use generateStaticParams()
instead of getStaticProps()
and getStaticPaths()
. Details can be found here.
Still in search of a good alternative for fetching markdown files from local directories without relying on 'fs'. Open to suggestions!