Recently, I encountered an issue with my TypeScript file when importing an mdx file.
import mdx from "./Layout.mdx";
After some research, I found a helpful resource that suggested a solution:
If you’re getting errors from TypeScript related to imports with an *.mdx extension, create an mdx.d.ts file in your types directory and include it inside your tsconfig.json.
// types/mdx.d.ts
declare module '*.mdx' {
let MDXComponent: (props: any) => JSX.Element
export default MDXComponent
}
Implementing this solution, I updated my folder structure as follows:
Root
-types
--mdx.d.ts
-src
--My tsx files
Surprisingly, the compiler stopped complaining about the import. However, I was puzzled by how it automatically recognized the d.ts file in the types folder, as I didn't reference it in my tsconfig.json:
{
"compilerOptions": {
"rootDir": "src",
"declaration": true,
"declarationDir": "build",
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom", "es2016", "es2017"],
"sourceMap": true,
"jsx": "react",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"noImplicitAny": true
},
"include": ["src/**/*"],
"exclude": [
"node_modules",
"build",
"storybook-static",
"src/**/*.stories.tsx",
"src/**/*.test.tsx"
]
}
It's worth noting that the issue was highlighted in Visual Code IDE, but the error disappeared once I placed the d.ts file in the types folder.
UPDATE: For further reference, here is the link to the package.json