Run TypeScript Files

验证:未记录
适用版本
未记录
验证范围
尚未登记验证记录。

本文缩写(英文全称与中文含义)
缩写 英文全称/名称 中文含义
API Application Programming Interface 应用程序编程接口
CI Continuous Integration 持续集成
ESM ECMAScript Modules JavaScript 标准模块系统
JS JavaScript JavaScript 编程语言
npm npm package manager Node.js 常用包管理器的名称,并非需强行展开的正式缩写

1. Important Points#

npx tsx helloworld.ts:
    npx resolves the local tsx binary; if absent, npm may fetch a temporary copy
    tsx transpiles and runs the .ts file; it does not replace typecheck

recommended for project scripts:
    install tsx as a devDependency
    expose a named package.json script
    run npm run <script>, not an unpinned remote tool

先运行 npm run typecheck;涉及写文件、调用付费 API 或批量操作时,脚本默认应支持 --dry-run,并把输入/输出目录写清楚。

2. tsx: Local Script Default#

创建 scripts/helloworld.ts:

const name: string = process.argv[2] ?? "World";

console.log(`Hello, ${name}!`);

一次性试验可直接运行:

npx tsx scripts/helloworld.ts
npx tsx scripts/helloworld.ts Codex

项目内安装并锁定版本:

npm install -D tsx typescript @types/node
{
  "scripts": {
    "hello": "tsx scripts/helloworld.ts",
    "hello:watch": "tsx watch scripts/helloworld.ts",
    "typecheck": "tsc --noEmit"
  }
}
npm run typecheck
npm run hello
npm run hello -- Codex

npm run <script> -- <args> 中第一个 -- 属于 npm,之后的参数才传给 TypeScript 脚本。tsx 适合 local dev、工具脚本与 watch;它通常走 esbuild 转换,运行前不会做完整 TypeScript typecheck。

3. Alternatives#

Method Command Use when Notes
tsx npx tsx file.ts 默认开发/脚本 ESM 体验好;另跑 tsc --noEmit
package script npm run hello -- Codex 项目共享脚本 推荐;版本和参数可审查
compile then Node tsc -p tsconfig.scripts.json && node dist-scripts/file.js CI / production-like job 最可预测;先 typecheck 再运行 JS
ts-node npx ts-node file.ts 已采用 ts-node 的旧项目 ESM 配置不同,不要与 tsx 混用
Node type stripping node file.ts 简单、现代 Node 脚本 不 typecheck、忽略 tsconfig,且只适合可擦除类型语法

Compile then Node#

对定时任务、发布脚本和 CI,优先让构建产物成为实际执行对象:

{
  "scripts": {
    "build:scripts": "tsc -p tsconfig.scripts.json",
    "hello": "npm run build:scripts && node dist-scripts/helloworld.js"
  }
}

tsconfig.scripts.json 可以继承主配置,只覆盖 rootDir、outDir 与 include。不要在 production service 中把 tsx 或 ts-node 当启动命令;构建后用 node dist/main.js。

ts-node#

# CommonJS project.
npx ts-node scripts/helloworld.ts

# ESM project; ts-node must be installed locally for stable behavior.
npx ts-node --esm scripts/helloworld.ts

ts-node 适合已经依赖它的项目。新项目在 tsx 与 ts-node 中二选一;二者的 ESM loader、source map 和 tsconfig 行为不同,混用会让排障变复杂。

Node Native TypeScript#

近期 Node 可直接执行一部分 .ts 文件的 type stripping。它只移除类型,不做 typecheck,不读取 tsconfig.json,也不支持需要运行时转换的 TypeScript 特性(例如 enum)。因此它适合语法简单、无构建工具依赖的小脚本;保留 npm run typecheck,并以项目实际 Node 版本的 node --help/官方文档为准。

4. Decision#

临时本地脚本:       npx tsx file.ts
团队长期脚本:       npm run named-script -- <args>
需要 watch:         tsx watch file.ts
CI / production job: tsc -> node dist/*.js
已有 ts-node 项目:  保持 ts-node,不在同一脚本混入 tsx
极简新 Node 脚本:   node file.ts + npm run typecheck

搜索文档

输入关键词,搜索所有文档。

↑ ↓ 选择 · Enter 打开 · Esc 关闭