我想使用 TypeScript 而不是 JS 来开发我的网站。所以我关注了NextJS's official to install TS从头开始,但是当我运行 npm run dev
时,出现 404 错误页面。
OK,下面是我的 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
。
{
"name": "MY_PROJECT_NAME",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"go": "next build && next start",
"debug": "NODE_OPTIONS='--inspect' next dev"
},
"dependencies": {
"@mdx-js/loader": "^1.6.22",
"@next/mdx": "^10.0.3",
"@types/node": "^14.14.14",
"@types/react": "^17.0.0",
"@types/styled-components": "^5.1.5",
"@types/webpack": "^4.41.25",
"autoprefixer": "^10.1.0",
"express": "^4.17.1",
"gray-matter": "^4.0.2",
"next": "^10.0.3",
"postcss": "^8.2.1",
"raw-loader": "^4.0.2",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-markdown": "^4.3.1",
"remark-emoji": "^2.1.0",
"remark-html": "^13.0.1",
"remark-images": "^2.0.0",
"styled-components": "^5.2.1",
"tailwindcss": "^2.0.2",
"typescript": "^4.1.3",
"webpack": "^4.44.0"
}
}
嗯,我的代码有什么问题吗?
当我将代码运行为 .jsx
时,所有事情都正常工作。但 .tsx
不起作用。
有谁知道这个问题吗?
-- 添加index.tsx --
import Layout from '../components/Layout'
export default () => (
<>
<Layout title="Kreimben::Home" isHome={true}>
<div className="flex justify-center text-center">
<div className="bg-gray-300 p-8 m-12 rounded-lg w-4/5 text-4xl font-serif">
Welcome to indie developer's website!
</div>
</div>
<main className="flex justify-center">
<div className="w-4/5 py-32 mb-12 shadow-xl rounded-lg bg-gradient-to-r from-teal-300 to-blue-500 text-center">
<p className="text-4xl font-serif">I code</p>
<p className="font-semibold text-6xl">iOS, macOS, and anything!</p>
</div>
</main>
</Layout>
</>
)
最佳答案
我刚刚从 @next/mdx
插件配置中解决了这个问题。当您切换到 Typescript 时,pageExtensions
应该是 [ts, tsx]
。
简而言之,完善正确的 ext 文件可以解决问题:
next.config.js
// ...
module.exports = withMDX({
pageExtensions: ['ts', 'tsx', 'md', 'mdx'], // Replace `jsx?` with `tsx?`
})
关于javascript - NextJS 无法识别 TypeScript 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65381667/