NextJS中文文档 - Typescript
Next.js 内置了 TypeScript 支持,当你使用 create-next-app
创建新项目时,会自动安装必要的包并配置适当的设置。
要将 TypeScript 添加到现有项目中,将文件重命名为 .ts
/ .tsx
。运行 next dev
和 next build
将自动安装必要的依赖项,并添加包含推荐配置选项的 tsconfig.json
文件。
提示:如果你已经有
jsconfig.json
文件,请将旧jsconfig.json
中的paths
编译器选项复制到新的tsconfig.json
文件中,然后删除旧的jsconfig.json
文件。
示例
类型检查 next.config.ts
你可以使用 TypeScript 并在 Next.js 配置中导入类型,方法是使用 next.config.ts
。
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
/* 这里是配置选项 */
}
export default nextConfig
提示:目前
next.config.ts
中的模块解析仅限于CommonJS
。这可能导致在next.config.ts
中加载仅 ESM 的包时出现不兼容问题。
当使用 next.config.js
文件时,你可以使用 JSDoc 在你的 IDE 中添加一些类型检查,如下所示:
js
// @ts-check
/** @type {import('next').NextConfig} */
const nextConfig = {
/* 这里是配置选项 */
}
module.exports = nextConfig
Incremental type checking
Since v10.2.1
Next.js supports incremental type checking when enabled in your tsconfig.json
, this can help speed up type checking in larger applications.
Disabling TypeScript errors in production
Next.js fails your production build (next build
) when TypeScript errors are present in your project.
If you'd like Next.js to dangerously produce production code even when your application has errors, you can disable the built-in type checking step.
If disabled, be sure you are running type checks as part of your build or deploy process, otherwise this can be very dangerous.
Open next.config.ts
and enable the ignoreBuildErrors
option in the typescript
config:
ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
typescript: {
// !! WARN !!
// Dangerously allow production builds to successfully complete even if
// your project has type errors.
// !! WARN !!
ignoreBuildErrors: true,
},
}
export default nextConfig
Good to know: You can run
tsc --noEmit
to check for TypeScript errors yourself before building. This is useful for CI/CD pipelines where you'd like to check for TypeScript errors before deploying.
Custom type declarations
When you need to declare custom types, you might be tempted to modify next-env.d.ts
. However, this file is automatically generated, so any changes you make will be overwritten. Instead, you should create a new file, let's call it new-types.d.ts
, and reference it in your tsconfig.json
:
json
{
"compilerOptions": {
"skipLibCheck": true
//...truncated...
},
"include": ["new-types.d.ts", "next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Version Changes
Version | Changes |
---|---|
v15.0.0 | next.config.ts support added for TypeScript projects. |
v13.2.0 | Statically typed links are available in beta. |
v12.0.0 | SWC is now used by default to compile TypeScript and TSX for faster builds. |
v10.2.1 | Incremental type checking support added when enabled in your tsconfig.json . |
/nextjs-cn/