«

2022年8月1日 ts-node 运行报错`Cannot find name 'console'.`

Mahalalel 发布于 阅读:5683 TypeScript


背景

最近小编在学习TypeScript,运行基本demo的时候,遇到一个报错,特此记录下。
异常如下:

D:\develop\nvm\v14.17.0\node_global\node_modules\ts-node\src\index.ts:859
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: ⨯ Unable to compile TypeScript:
demo.ts:15:3 - error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.

15   console.log(a);
     ~~~~~~~

    at createTSError (D:\develop\nvm\v14.17.0\node_global\node_modules\ts-node\src\index.ts:859:12)
    at reportTSError (D:\develop\nvm\v14.17.0\node_global\node_modules\ts-node\src\index.ts:863:19)
    at getOutput (D:\develop\nvm\v14.17.0\node_global\node_modules\ts-node\src\index.ts:1077:36)
    at Object.compile (D:\develop\nvm\v14.17.0\node_global\node_modules\ts-node\src\index.ts:1433:41)
    at Module.m._compile (D:\develop\nvm\v14.17.0\node_global\node_modules\ts-node\src\index.ts:1617:30)
    at Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Object.require.extensions.<computed> [as .ts] (D:\develop\nvm\v14.17.0\node_global\node_modules\ts-node\src\index.ts:1621:12)
    at Module.load (internal/modules/cjs/loader.js:933:32)
    at Function.Module._load (internal/modules/cjs/loader.js:774:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {
  diagnosticCodes: [ 2584 ]
}

问题是demo.ts:15:3 - error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.;

原因就在于,无法识别console函数。

解决

1、全局安装 ts-node 运行依赖包

命令如下:

npm install -g tslib @types/node

@types/node解释

关于@types,可以参考下 深入理解TypeScript @types

类型定义中,可以看到 @types一个高质量的TypeScript类型定义的仓库

@types/node是TS文件做声明作用的。

tslib解释

npm库中对其定义为这是一个包含所有 TypeScript 辅助函数的 TypeScript运行时库

2、降低ts-node版本

网络上还有一种方法,降低ts-node的版本,可以解决这个问题,

注:此种办法,并未做测试。

TypeScript