TypeScript

TypeScript 开发指南

常用配置

运行环境

nvm install lts/iron # v20.18.*
npm i -g npm 
npm i -g typescript
npm i -g ts-node   # Run ts file directly.

# Install locally for different versions
npm install typescript --save-dev
npm install -D ts-node
npx tsc --version

VS Code

launch.json

ts-node 可以直接运行 .ts 文件。

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "TS: Compiled JS",
      "type": "node",
      "request": "launch",
      "program": "${fileDirname}${/}${fileBasenameNoExtension}.js"
    },
    {
      "name": "Deno: File",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "deno",
      "program": "${file}",
      "cwd": "${workspaceFolder}",
      "runtimeArgs": [
        "run"
      ],
      /* Convenient for Debug. */
      "internalConsoleOptions": "openOnSessionStart", /* If open debug console. */
    },
    {
      "name": "ts-node: File",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/ts-node",
      "runtimeArgs": [
        "--transpile-only",
        // if you use esm
        "--esm"
      ],
      "program": "${file}",
      "cwd": "${workspaceRoot}",
      "internalConsoleOptions": "openOnSessionStart",
      "skipFiles": [
        "<node_internals>/**",
        "node_modules/**"
      ]
    },
  ]
}

tasks.json

{
    // Run through Menu: Terminal > Run Build Task...

    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Compile TypeScript",
            "type": "typescript",
            "tsconfig": "tsconfig.json",
            "problemMatcher": [
                "$tsc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true,
            },
            "presentation": {
                "echo": false,
                "reveal": "silent",
                "revealProblems": "onProblem",
                "panel": "shared",
                "close": true,
                "clear": false,
            }
        },

    ]
}

常用命令行

命令 作用
tsc --version 检查版本
tsc --init 生成 tsconfig.js
Author: njun
njun's picture
Updated: 2024/11/28