它可以很好地渲染组件到网站,但输入mdx文件时显示错误。
输入错误信息:找不到模块“@/articles/good.mdx”或其对应的类型声明。
我在stack overflow中发现了大量的注解。但它仍然没有解决这个问题。尝试安装 @mdx-js/mdx,同样不起作用。
import React from "react";
import Layout from "@/components/Layout/index";
import Good from "@/articles/good.mdx"; // this line show typescript error
const index = () => {
return (
<Layout>
<Good />
</Layout>
);
};
export default index;
Package.json(删除了一些不相关的内容)
{
"dependencies": {
"@next/mdx": "^10.2.0",
"@types/react-transition-group": "^4.4.1",
"next": "10.1.3",
"next-seo": "^4.24.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-query": "^3.13.11",
"react-transition-group": "^4.4.1"
},
"devDependencies": {
"@mdx-js/loader": "^1.6.22",
"@types/node": "^15.0.1",
"@types/react": "^17.0.4",
"@types/webpack-env": "^1.16.0",
"autoprefixer": "^10.2.5",
"typescript": "^4.2.4"
}
}
tsconfig.json(删除了一些无关的内容)
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"types": [
"node",
"webpack-env"
]
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"**/*.mdx",
],
"exclude": [
"node_modules"
]
}
3条答案
按热度按时间xghobddn1#
要解决此问题,请创建一个名为
mdx.d.ts
的文件,并将其放置在项目的根目录或根目录下的types
文件夹中,然后粘贴以下代码:这定义了
.mdx
文件的全局类型,并告诉typescript从.mdx
文件默认导入返回(props: any) => JSX.Element
,这使得在.tsx
文件中使用<YourMdxComponent />
是安全的。5tmbdcev2#
mdxjs现在支持类型
gv8xihay3#
更方便的方法是安装类型
yarn add @types/mdx
。然后将这些类型包含在tsconfig.ts
中如果要从mdx文件(如
import YourMdxContent, { SomeComponent } from './YourMdxFile.mdx'
你会得到一个错误:
Module '"*.mdx"' has no exported member 'SomeComponent'. Did you mean to use 'import SomeComponent from "*.mdx"' instead?
如果发生这种情况,您需要重新声明mdx模块:
不需要重新声明MDXContent,因为它已经从
types
继承。