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

Angular升级后出现Cannot find module 'http'(@types/cors引发)求助

Angular升级后TS2307: 找不到模块'http'类型声明的问题解决

问题详情

升级Angular、Material及相关依赖库后,编译时抛出以下错误:

Error: node_modules/@types/cors/index.d.ts:8:37 - error TS2307: Cannot find module 'http' or its corresponding type declarations.
import { IncomingHttpHeaders } from 'http';

当前环境版本:

  • Angular: 14.1.3
  • @types/node(开发依赖): 18.7.13
  • TypeScript: 4.6.4

错误来自@types/cors/index.d.ts,属于@angular-devkit/build-angular (14.1.3)的间接依赖,并非项目直接引入的包。

已尝试但未解决问题的操作:

  • 在tsconfig.json的compilerOptions中添加typeRoots和types配置
  • 更新相关库并测试多版本组合
  • 安装@types/node(StackOverflow常见方案)
  • 删除并重新安装node_modules
  • 将Node.js降级至16.10.0

可行解决方案

1. 安装与TypeScript兼容的@types/node版本

Angular 14.1.x适配的TypeScript版本是4.6.x,而@types/node 18.x和TS4.6存在兼容性差异。建议安装对应Node 16版本的@types/node:

npm install @types/node@16 --save-dev

2. 调整tsconfig.json的类型配置

确保tsconfig.json的compilerOptions中显式包含node类型,同时关闭skipLibCheck(避免跳过类型检查掩盖问题):

{
  "compilerOptions": {
    // 其他已有配置...
    "types": ["node"],
    "skipLibCheck": false
  }
}

修改后重新执行编译命令,验证错误是否消失。

3. 强制锁定@types/cors版本

由于错误源于@angular-devkit/build-angular的间接依赖冲突,可通过resolutions强制指定兼容的@types/cors版本:

  • 使用npm:
    1. 先安装依赖强制解析工具:
    npm install npm-force-resolutions --save-dev
    
    1. 在package.json中添加以下配置:
    {
      "resolutions": {
        "@types/cors": "^2.8.13"
      },
      "scripts": {
        "preinstall": "npx npm-force-resolutions"
      }
    }
    
    1. 重新安装依赖:
    npm install
    
  • 使用yarn:
    直接在package.json中添加:
    {
      "resolutions": {
        "@types/cors": "^2.8.13"
      }
    }
    
    然后执行:
    yarn install
    

4. 验证Angular CLI配置

检查angular.json中build配置的tsConfig字段,确认指向的是正确的tsconfig.json文件,避免因配置文件不一致导致类型未被加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:57:24