如何在TypeScript中使用Node.js内置模块如assert?
问题:Node.js中assert模块无法找到类型声明
我没法让assert()正常运行,它是Node.js的内置模块,但TypeScript编译时提示找不到模块或对应的类型声明。
源码中的导入语句:
import assert from 'node:assert/strict'
编译时报错:
error TS2307: Cannot find module 'node:assert/strict' or its corresponding type declarations.
我的package.json内容:
{ "name": "untitled", "packageManager": "yarn@3.5.0", "devDependencies": { "typescript": "^5.0.4" } }
tsconfig.json配置:
{ "compilerOptions": { "module": "commonjs", "target": "es2015", "declaration": true, "outDir": "./dist" }, "include": [ "src/**/*" ] }
使用的版本:
- Node.js 18.16.0
- TypeScript 5.0.4
解决方案
1. 安装Node.js类型声明依赖
TypeScript本身不包含Node.js内置模块的类型定义,需要安装@types/node来提供这些声明:
yarn add -D @types/node
2. 配置tsconfig.json
在compilerOptions中添加"types": ["node"],确保TypeScript识别Node.js的类型声明:
{ "compilerOptions": { "module": "commonjs", "target": "es2015", "declaration": true, "outDir": "./dist", "types": ["node"] }, "include": [ "src/**/*" ] }
3. 验证修复
重新运行TypeScript编译命令,之前的模块找不到错误应该会消失,assert模块的类型提示也能正常生效。
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

