【发布时间】:2021-11-06 18:19:52
【问题描述】:
我有一个问题,可能与将 NextJs 与 typescript 一起使用有关。
例子:
// /pages/index.tsx
import _ from 'lodash'
export const MyComponent = () => {
return {
<ul>{
_.map(someArray, el => <li>{el}</li>) // Error: Module not found: Can't resolve 'fs'
}</ul>
}
我自己的函数也有同样的错误,不仅是 lodash 函数。
如果我将 .ts 文件中的函数导入到 .tsx 文件中,然后在 TSX 中执行它,我会收到 ModuleNotFound 错误,有时也会出现 ModuleNotFoundError: Module not found: Error: Can't resolve 'child_process'。但是,我可以导入并执行从 .js 文件导入的自定义函数。
这是我的 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"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
package.json:
"dependencies": {
"@mdx-js/loader": "^1.6.22",
"@next/mdx": "^11.0.1",
"lodash": "^4.17.21",
"next": "^11.0.1",
"next-mdx-remote": "^3.0.4",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-markdown": "^6.0.2",
"typescript": "^4.3.5"
},
"devDependencies": {
"@types/lodash": "^4.14.172",
"@types/react": "^17.0.20",
"@typescript-eslint/eslint-plugin": "^4.30.0",
"eslint": "^7.32.0",
"eslint-config-next": "^11.1.2"
}
}
下一个配置:
const withMDX = require('@next/mdx')({
extension: /\.mdx$/
})
module.exports = withMDX({
pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'],
})
我想我在配置 NextJs 以使用 TSX 和 Typescript 时遗漏了一些东西。 谢谢!
【问题讨论】:
标签: typescript next.js tsx react-tsx