Next.js + MDX Enhanced Not Allowing Typescript Template Files

Viewed 295

I have pretty much followed the tutorial here https://magrippis.com/blog/2020/how-to-setup-MDX-in-Nextjs, using this Next.js plugin https://github.com/hashicorp/next-mdx-enhanced, however when I try to add a template file with a .tsx or .ts extension or reference another component within the template file that is a .tsx or .ts I get an error saying "Module not found". I can use other .tsx files just not within the templates, for example, I can use it for pages or components not references within the templates.

next.config.js file:

const withPlugins = require('next-compose-plugins');
const rehypePrism = require('@mapbox/rehype-prism');

const mdx = require('next-mdx-enhanced')({
  defaultLayout: true,
  fileExtensions: ['mdx', 'md'],
  rehypePlugins: [rehypePrism],
});

// you may tweak other base Next options in this object
// we are using it to tell Next to also handle .md and .mdx files
const nextConfig = { 
  pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'mdx', 'md'],
  future: {
    webpack5: false,
  },

};

module.exports = withPlugins(
  [
    mdx,
    // you may add more plugins, and their configs, to this array
  ],
  nextConfig
)

.babelrc file (Not sure if this matters):


{
    "presets": ["next/babel"],
    "plugins": ["import-glob-array"]
  }
1 Answers

I'm not sure why but I had to update the webpack config to include 'ts' and 'tsx' extensions. Below is the code from my next.config.js that I used to accomplish this, which can be compared to my original one above to see the difference.

const withPlugins = require('next-compose-plugins');
const rehypePrism = require('@mapbox/rehype-prism');

const mdx = require('next-mdx-enhanced')({
  defaultLayout: true,
  fileExtensions: ['mdx', 'md'],
  rehypePlugins: [rehypePrism],
});

const webPackConfig = (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
  // Note: we provide webpack above so you should not `require` it

  // Add support for .tsx and .ts templates
  config.resolve.extensions.push('.tsx', '.ts');

  // Important: return the modified config
  return config
};

// you may tweak other base Next options in this object
// we are using it to tell Next to also handle .md and .mdx files
const nextConfig = { 
  pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'mdx', 'md'],
  webpack: webPackConfig,
};

module.exports = withPlugins(
  [
    mdx,
    // you may add more plugins, and their configs, to this array
  ],
  nextConfig
)
Related