如何解决VSCode中可运行Node.js代码的TypeScript编译错误?
解决Node.js性能测量代码TypeScript编译报错与VSCode波浪线问题
检查tsconfig.json关键配置
确保你的tsconfig.json里开启了Node.js相关类型支持:
- 在
compilerOptions中添加"types": ["node"],明确让TypeScript加载Node.js的类型定义 - 把
"target"设置为对应你Node.js版本的ES标准(比如Node.js 18+设为"ES2020"及以上) - 开启
"moduleResolution": "node",保证模块解析逻辑符合Node.js规则
示例配置片段:
{ "compilerOptions": { "target": "ES2020", "moduleResolution": "node", "types": ["node"], "strict": true, "esModuleInterop": true } }
验证@types/node版本匹配
- 执行
npm list @types/node查看已安装版本,确保它和你本地Node.js版本对应(比如Node.js 18.x就装@types/node@18.x,版本差太多会导致类型缺失) - 版本不匹配的话,卸载重装对应版本:
npm uninstall @types/node npm install @types/node@<你的Node版本号,比如18> --save-dev
修正代码的类型引用方式
Node.js的performance API在TypeScript里推荐明确导入模块,避免全局变量识别问题:
import { performance } from 'node:perf_hooks'; // 性能测量示例 const start = performance.now(); // 执行你的业务逻辑 const end = performance.now(); console.log(`耗时:${end - start}ms`);
如果一定要用全局performance,可以加一行类型声明兜底:
declare const performance: typeof import('node:perf_hooks').performance;
刷新VSCode的TypeScript服务
按Ctrl+Shift+P(Windows/Linux)或Cmd+Shift+P(Mac),输入TypeScript: Restart TS Server重启服务,清除类型缓存后波浪线会消失。
重新执行编译
完成以上步骤后,再跑tsc --build就能正常编译了。
内容的提问来源于stack exchange,提问作者chuacw
相关产品推荐
相关产品推荐

