Make remarkCodeHike work at Next.js edge runtime
The issue
I am trying to integrate Code Hike into a Next.js project using the Edge Runtime. I referred to this project:
https://github.com/code-hike/examples/tree/next-mdx-remote/with-next-mdx-remote-rsc
and added this line of code to page.tsx:
export const runtime = "edge"
I noticed that page.tsx import fs from "fs", which is not available in edge. So I just hard code source to test if Code Hike works.
- import { promises as fs } from "fs"
+ export const runtime = "edge"
export default async function Home() {
- const source = await fs.readFile("./content/index.md", "utf-8")
+ const source = "# title";
const { content } = await compileMDX({
source,
components,
options: {
Unfortunately, it threw an compile error caused by import "fs" module inside of codehike/dist/mdx.js.
Then I found the problematic code:
https://github.com/code-hike/codehike/blob/7e7b78d75ec24db7293b5d01475f3cf67c20bcea/packages/codehike/src/mdx/0.import-code-from-path.ts#L56-L64
When using Webpack, dynamic imports with import() can prevent exceptions from being caught by try-catch.
Even if I didn’t use Code Hike’s !from feature to import external code.
The solution
Changing import to require resolves this issue. Because require imports modules at runtime, while import does so at compile time.
The latest updates on your projects. Learn more about Vercel for Git ↗︎
| Name | Status | Preview | Comments | Updated (UTC) |
|---|---|---|---|---|
| codehike.org | ❌ Failed (Inspect) | Dec 9, 2024 7:00am |
@pomber is attempting to deploy a commit to the codehike Team on Vercel.
A member of the Team first needs to authorize it.
Try codehike from this pull request in your project with:
npm i https://pkg.pr.new/codehike@489