Skip to content

ts-node

ts-node 的简单使用

新建文件夹 ts-node-practise。

然后执行一下命令:

shell
pnpm init

pnpm i ts-node typescript -D

npx tsc --init

设置 pacakge.json:

json
{
  "name": "ts-node-practise",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "dev": "ts-node-esm main.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ts-node": "^10.9.1",
    "typescript": "^5.0.4"
  }
}

然后还需要设置 tsconfig.json 里 compilerOptions.allowImportingTsExtensions 为 true。

json
"allowImportingTsExtensions": true

之后就可以在 ts 文件里写 ts 代码了。

main.ts

ts
import {speak} from './index.js'

const a: number = 1
console.log(a)
speak()

index.ts

ts
export function speak() {
  console.log('speak asdf');
}

开启 swc 转换

https://typestrong.org/ts-node/docs/swc

需要下载 swc 的相关依赖。

shell
pnpm i -D @swc/core

然后指定参数:

shell
ts-node --swc index.ts

支持使用 es 模块

使用 ts-node-esm script.ts 命令,与 ts-node --esm 命令等效。

Released under the MIT License.