tsconfig.json
了解 Nuxt 如何在项目的不同部分管理 TypeScript 配置。
Nuxt 会自动生成多个 TypeScript 配置文件(.nuxt/tsconfig.app.json、.nuxt/tsconfig.server.json、.nuxt/tsconfig.node.json 和 .nuxt/tsconfig.shared.json),其中包含为你项目推荐的 TypeScript 基础配置、对自动导入、API 路由类型、路径别名等的引用。
你的 Nuxt 项目应在项目根目录包含以下 tsconfig.json 文件:
tsconfig.json
{
"files": [],
"references": [
{
"path": "./.nuxt/tsconfig.app.json"
},
{
"path": "./.nuxt/tsconfig.server.json"
},
{
"path": "./.nuxt/tsconfig.shared.json"
},
{
"path": "./.nuxt/tsconfig.node.json"
}
]
}
我们不建议直接修改此文件的内容,因为这样做可能会覆盖掉 Nuxt 或其他模块所依赖的重要设置。请改为通过
nuxt.config.ts 来扩展它。在此阅读更多关于 Nuxt 项目不同类型上下文的内容。
扩展 TypeScript 配置
你可以在 nuxt.config.ts 文件中自定义 Nuxt 项目的 TypeScript 配置:用 typescript.tsConfig 一次性为所有上下文设置共享的 compilerOptions,并分别对每个上下文(app、shared、node 和 server)单独覆盖。
nuxt.config.ts
// @errors: 2353
export default defineNuxtConfig({
typescript: {
// 为每个生成的 tsconfig 设置共享 compilerOptions
tsConfig: {
compilerOptions: {
// ...
},
},
// 自定义 tsconfig.app.json
appTsConfig: {
// ...
},
// 自定义 tsconfig.shared.json
sharedTsConfig: {
// ...
},
// 自定义 tsconfig.node.json
nodeTsConfig: {
// ...
},
// 自定义 tsconfig.server.json
serverTsConfig: {
// ...
},
},
})
在
typescript.tsConfig 中设置的大多数 compilerOptions 会在所有上下文间共享,但有少数例外。与 DOM 和 Vue 相关的选项(如 lib、jsx 和 jsxImportSource)只对应用代码有意义,因此仅应用于 tsconfig.app.json。Nuxt 还会按上下文管理 types、paths 和 noEmit(node、shared 和 server 配置故意不输出任何内容、也不扫描环境类型),因此在 typescript.tsConfig 中设置这些项不会改变它们。当你需要覆盖它们时,请使用对应的按上下文选项(appTsConfig、nodeTsConfig、sharedTsConfig 或 serverTsConfig)。typescript.serverTsConfig 与 nitro.typescript.tsConfig 都扩展 tsconfig.server.json 且会保持同步,因此设置其中任意一个效果相同。建议优先使用 typescript.serverTsConfig,以便将这四个上下文集中在一处管理。