You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenAPI TypeScript生成文件无法在Next.js构建中排除类型检查

问题:Next.js构建时无法排除OpenAPI生成文件的TypeScript检查

我有一个Next.js + React + TypeScript项目,基于api-docs.yaml用OpenAPI Generator生成类型定义,在项目里按需导入这些类型。虽然所有生成文件顶部都加了/* tslint:disable */和/* eslint-disable */,但执行next build时还是没法把这些文件排除在TypeScript类型检查之外。

项目结构

api/
src/
tsconfig.json

当前配置文件

tsconfig.json

{
  "compilerOptions": {
    "strict": false,
    "noImplicitAny": false,
    "noImplicitThis": true,
    "alwaysStrict": false,
    "types": ["jest", "@testing-library/jest-dom"],
    "target": "ES2022",
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "lib": ["dom", "dom.iterable", "ESNext"],
    "allowJs": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "ESNext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      // "@features/*": ["./src/features/*"],
      "@/*": ["src/*"],
      "@/api/*": ["api/*"],
      "react": [ "./node_modules/@types/react" ]
    },
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true
  },
  "include": [
    "next-env.d.ts",
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/types/tailwind-datepicker-react.d.ts"
  ],
  "exclude": [
    "node_modules",
    "api/**/*"
  ]
}

.eslintignore

api/**/*

.eslintrc.json

{
  "extends": "next/core-web-vitals",
  "ignorePatterns":  ["api/**/*.ts"]
}

解决办法

1. 单独配置构建用的tsconfig文件

Next.js默认用根目录的tsconfig.json做构建检查,有时候直接加exclude不生效,建议新增tsconfig.build.json专门用于构建:

{
  "extends": "./tsconfig.json",
  "exclude": [
    "node_modules",
    "api/**/*",
    "jest.config.ts",
    "src/**/*.test.ts",
    "src/**/*.test.tsx"
  ]
}

然后在next.config.js里指定这个配置:

/** @type {import('next').NextConfig} */
const nextConfig = {
  typescript: {
    tsconfigPath: './tsconfig.build.json',
  },
}

module.exports = nextConfig

2. 用类型导入+skipLibCheck规避检查

如果项目里需要导入api目录的类型,改用类型专属导入:

import type { User, Order } from '@/api/models'

同时确保tsconfig.json里的skipLibCheck保持true,这个配置会跳过对第三方/生成类型文件的完整类型检查,只读取类型信息。

3. 调整OpenAPI Generator的生成参数

直接让生成的文件自带TypeScript忽略标记,比如在生成命令里加参数生成.d.ts声明文件,或者添加@ts-nocheck注释:

openapi-generator-cli generate -i api-docs.yaml -g typescript-axios -o api/ --additional-properties=supportsES6=true,typescriptThreePlus=true,skipTypeCheck=true

生成的文件会自动带上// @ts-nocheck,从根源上让TypeScript跳过检查。

4. 检查是否有间接依赖导致的检查

如果以上方法都没用,可能是某个src/下的文件导入了api目录的非类型代码(比如生成的API请求函数),这时候需要把这些生成的工具函数也用@ts-nocheck标记,或者确认它们已经被包含在exclude规则里。


内容的提问来源于stack exchange,提问作者que1326

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 00:25:09