I created a unique plugin that converts frontmatter in MDX files to a constant export called frontMatter
. Let's take the file a.mdx
as an example:
---
title: "Some Title"
---
# Content
When this file is imported into a Next.js Page directly, it gets transformed at compile-time like this:
# Content
export const frontMatter = {
title: "Some Title"
}
To import in a Typescript & Next.js page file, I use the following syntax:
import AComponent, { frontMatter } from "a.mdx"
The custom export of frontMatter
works fine. However, there are issues with the Typescript compiler not recognizing this custom export unless explicitly exported from the file. Here is my current definition in tsconfig:
declare module '*.mdx' {
import { MDXProps } from 'mdx/types'
const MDXComponent: (props: MDXProps) => JSX.Element
const frontMatter: { [key: string]: any }
export { frontMatter }
export default MDXComponent
}
This approach doesn't work as expected. Interestingly, if I declare another module within the same file, the import works perfectly:
declare module '*.myFile' {
export const value
}
An error message that I encounter states:
Module 'index.mdx' has no exported member 'frontMatter'. Did you mean to use 'import frontMatter from "index.mdx"' instead?
It appears that there might be something conflicting with the mdx definitions despite trying multiple solutions. Below is a snippet from my tsconfig.json file:
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
... Some remappings here
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"**/*.mdx",
".next/types/**/*.ts",
"THE MODULE DECLARATION FILE"
],
"exclude": ["node_modules"]
}