TypeScript
Next.js 为构建 React 应用提供了 TypeScript 优先的开发体验。
它内置了 TypeScript 支持,可自动安装必要的包并配置正确的设置。
新建项目
create-next-app 现在默认包含 TypeScript。
npx create-next-app@latest现有项目
通过将文件重命名为 .ts / .tsx 来为项目添加 TypeScript。运行 next dev 和 next build 会自动安装必要的依赖项,并添加包含推荐配置选项的 tsconfig.json 文件。
如果您已有 jsconfig.json 文件,请将 paths 编译器选项从旧的 jsconfig.json 复制到新的 tsconfig.json 文件中,并删除旧的 jsconfig.json 文件。
最低 TypeScript 版本
强烈建议至少使用 TypeScript v4.5.2 版本,以获取诸如 导入名称上的类型修饰符 和 性能改进 等语法特性。
静态生成和服务端渲染
对于 getStaticProps、getStaticPaths 和 getServerSideProps,您可以分别使用 GetStaticProps、GetStaticPaths 和 GetServerSideProps 类型:
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
export const getStaticProps = (async (context) => {
// ...
}) satisfies GetStaticProps
export const getStaticPaths = (async () => {
// ...
}) satisfies GetStaticPaths
export const getServerSideProps = (async (context) => {
// ...
}) satisfies GetServerSideProps须知:
satisfies是在 TypeScript 4.9 中添加的。我们建议升级到最新版本的 TypeScript。
API 路由
以下是如何为 API 路由使用内置类型的示例:
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'John Doe' })
}您还可以对响应数据进行类型化:
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
name: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
res.status(200).json({ name: 'John Doe' })
}自定义 App
如果您有 自定义 App,可以使用内置类型 AppProps,并将文件名更改为 ./pages/_app.tsx,如下所示:
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}路径别名和 baseUrl
Next.js 自动支持 tsconfig.json 中的 "paths" 和 "baseUrl" 选项。
您可以在 模块路径别名文档 中了解更多关于此功能的信息。
检查 next.config.js 类型
next.config.js 文件必须是 JavaScript 文件,因为它不会被 Babel 或 TypeScript 解析,但您可以使用 JSDoc 在 IDE 中添加一些类型检查,如下所示:
// @ts-check
/**
* @type {import('next').NextConfig}
**/
const nextConfig = {
/* 此处为配置选项 */
}
module.exports = nextConfig增量类型检查
自 v10.2.1 起,Next.js 支持在 tsconfig.json 中启用 增量类型检查,这有助于在大型应用中加快类型检查速度。
忽略 TypeScript 错误
当项目中存在 TypeScript 错误时,Next.js 会使您的 生产构建 (next build) 失败。
如果您希望 Next.js 即使在应用存在错误时也能危险地生成生产代码,可以禁用内置的类型检查步骤。
如果禁用,请确保在构建或部署过程中运行类型检查,否则这可能非常危险。
打开 next.config.js 并在 typescript 配置中启用 ignoreBuildErrors 选项:
module.exports = {
typescript: {
// !! 警告 !!
// 危险地允许生产构建在项目存在类型错误时成功完成。
// !! 警告 !!
ignoreBuildErrors: true,
},
}