首页 > 解决方案 > Next.js + MDX 增强不允许 Typescript 模板文件

问题描述

我已经非常关注这里的教程https://magrippis.com/blog/2020/how-to-setup-MDX-in-Nextjs,使用这个 Next.js 插件https://github.com/hashicorp/next- mdx-enhanced,但是当我尝试添加扩展名为 .tsx 或 .ts 的模板文件或引用模板文件中的另一个 .tsx 或 .ts 组件时,我收到一条错误消息,提示“未找到模块”。我可以使用不在模板中的其他 .tsx 文件,例如,我可以将它用于模板中没有引用的页面或组件。

next.config.js 文件:

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 文件(不确定这是否重要):


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

标签: next.js

解决方案


我不知道为什么,但我不得不更新 webpack 配置以包含 'ts' 和 'tsx' 扩展。下面是我用来完成此操作的 next.config.js 中的代码,可以将其与上面的原始代码进行比较,以查看差异。

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
)

推荐阅读