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

项目中TypeScript编译错误求助:lint-staged中tsc执行失败

解决lint-staged中tsc命令执行异常的问题

问题背景

项目中lint-staged在pre-commit钩子可正常触发,但其中的tsc命令执行异常,已调整根目录下的tsconfig配置无效,报错包含模块找不到、JSX flag缺失、clsx导入错误三类。

现有配置

lint-staged(package.json)

"lint-staged": {
  "src/**/*.{ts,tsx}": ["tsc --skipLibCheck --noEmit"]
}

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src",
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "esnext",
    "target": "es5",
    "strict": true,
    "jsx": "react-jsx",
    "allowJs": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "paths": {
      "@/*": ["*"]
    }
  },
  "ts-node": {
    "compilerOptions": {
      "module": "CommonJS"
    }
  }
}

报错信息

✖ tsc --skipLibCheck --noEmit:
src/pages/main/ui/main.tsx(1,28): error TS2307: Cannot find module '@/shared/ui/typography' or its corresponding type declarations.
src/pages/main/ui/main.tsx(5,5): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
src/pages/main/ui/main.tsx(6,7): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
src/pages/main/ui/main.tsx(12,7): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
src/shared/ui/typography/ui/typography.tsx(3,8): error TS1259: Module "C:/Users/Happy/Desktop/front-cn/node_modules/clsx/clsx" can only be default-imported using the 'esModuleInterop' flag
src/shared/ui/typography/ui/typography.tsx(25,5): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.

项目目录结构

项目根目录/
├── tsconfig.json
├── package.json
└── src/
    ├── pages/
    │   └── main/
    │       └── ui/
    │           └── main.tsx
    └── shared/
        └── ui/
            └── typography/
                └── ui/
                    └── typography.tsx

问题根源

lint-staged默认会将暂存的单个文件路径传递给tsc,此时tsc进入「文件模式」——该模式下会忽略tsconfig中的paths、jsx、esModuleInterop等关键配置,导致各类报错。

解决方案

方案1:强制tsc使用项目模式

修改lint-staged配置,给tsc命令添加--project参数指定tsconfig路径,确保tsc始终以项目模式运行:

"lint-staged": {
  "src/**/*.{ts,tsx}": ["tsc --skipLibCheck --noEmit --project ./tsconfig.json"]
}

方案2:使用tsc-files提升效率

若项目体积较大,全量类型检查耗时久,推荐使用tsc-files工具——它仅检查指定文件,但仍会读取tsconfig的完整配置:

  1. 安装依赖:
npm install --save-dev tsc-files
  1. 更新lint-staged配置:
"lint-staged": {
  "src/**/*.{ts,tsx}": ["tsc-files --skipLibCheck --noEmit"]
}

验证方法

执行以下命令测试配置是否生效:

npx lint-staged --allow-empty

内容的提问来源于stack exchange,提问作者Глеб Кодрик

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:12:37