4

I want to use MDX in next.js and remark-gfm plugin. I found Next.js Docs about MDX and follow this. and add import statement.

// next.config.js
import remarkGfm from 'remark-gfm;'

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [remarkGfm],
    rehypePlugins: []
  }
})

module.exports = withTM(
  withMDX({
  pageExtensions: ['js', 'jsx', 'md', 'mdx'],
  })
)

I executed npm run dev, and error occurs. SyntaxError: Cannot use import statement outside a module

I tried changing import to require, but another error occurs.

Error [ERR_ERQUIRE_ESM]: require() of ES Module /home/me/myblog/node_modules/remark-gfm/index.js from /home/me/myblog/next.config.js not supported.

How can i import remark-gfm? Is it impossible?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
baba1
  • 49
  • 3
  • I cannot resolve this error. To convert mdx to JSX with plugins, I used `compile` function at @mdx-js/mdx. `compile` return JSX builder function in string format and I have to convert it to Function and Call this function like this `const JSXObject = Function(compiled)(React)` it's complicated and not elegant way. – baba1 Mar 26 '22 at 15:13
  • I am reasonably certain I've seen answers to this question here on StackOverflow. Have you searched? As I recall, one solution relates to needing a `package.json` file with something like `type="module"`. – ScottWelker Apr 01 '22 at 00:04

1 Answers1

2

I got it to work by changing the file name of next.config.js to next.config.mjs to support ES Modules.

File: next.config.mjs

import nextMdx from '@next/mdx';
import remarkGfm from 'remark-gfm;'

const withMDX = nextMdx({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [remarkGfm],
    rehypePlugins: []
  }
});

const nextConfig = {
  reactStrictMode: true,
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'],
};

export default withMDX(nextConfig);
codingwithmanny
  • 1,126
  • 8
  • 20