如何运行 ts 文件

notion image
在 VSCode 中安装扩展 Code Runner,我创建了一个 .ts 文件,点击运行按钮,但提示
'ts-node' 不是内部或外部命令'ts-node' is not recognized as an internal or external command
解决方法是全局安装 ts-node,例如:
但在我安装之后,错误确实消失了,却又提示另一个错误
所以我认为或许不止我一个人对于如何运行 ts 文件有疑问,所以本篇文章就来介绍一下如何在 VSCode 中运行 ts 文件,以及回到最初的问题,如何在 code runner 中运行 ts 文件。

如何运行 ts 文件

我们准备一个简单的的 ts 文件,命名为 index.ts,来作为测试的文件。

bun 运行 ts 文件(目前最推荐)

notion image

使用 tsc 将 ts 编译为 js,然后 node 运行

TypeScript Compiler (tsc) 是 TypeScript 的编译器,它可以将 TypeScript 代码编译为 JavaScript 代码。我们可以使用 tsc 命令来编译 TypeScript 文件。
notion image

tsx (TypeScript Executer) 运行 ts 文件

notion image

Node.js V22.7.0 直接运行文件

notion image

ts-node 运行 ts 文件(不推荐)

notion image
这个问题频繁出现于 ts-node 的 issues 中,有一个讨论甚至到了 70+ 也没有关闭
notion image
要解决这里的报错,需要做几件事情:
  1. 必须要有 package.json 并且 "type": "module"
    1. 如果没有 package.json, 运行 npm init -y 生成 package.json
  1. tsconfig.json 中 "module" 不能是 "commonjs" ,必须要有 'module': 'ESNext' 或者 'module': 'ES6'。
    1. 如果没有 tsconfig.json, 运行 npx tsc --init 生成 tsconfig.json
  1. 运行的时候必须要有 --loader ts-node/esm
notion image

如何在 coder runner 中运行 ts 文件

最简单的方法:在 code-runner.executorMap 中修改 typescript 的配置:
也可以这样写,然后会生成一个 js 文件,然后运行 js 文件:
不过这样的速度是比较慢的
notion image
  • 使用 bun $fullFileName: 耗时:0.295 秒
  • 使用 tsc tsc $fullFileName && node $fileNameWithoutExt.js:
    • 耗时:2.523 秒

总结

无论是运行 ts 文件还是在 code runner 中运行 ts 文件,最推荐的方式是使用 bun 来运行 ts 文件。它的速度和开箱即用的特性都非常好。
最不推荐的是 ts-node,需要有很严格的配置,且官方没有提供明确的文档来说明如何配置,更多的是靠开源社区的讨论来解决问题。
上一篇
南宁三天之旅
下一篇
pip安装和运行openwebui

相关文章

2024-W03

2024-07-11