VS Code 中手动和直接运行TS代码

188 阅读2分钟

前置准备

  1. 确保你的电脑已安装 Node.js(TS 编译和运行都依赖它)。

  2. 打开 VS Code 终端(快捷键 `Ctrl +``),全局安装 TypeScript 编译器:

    npm install -g typescript
    
  3. 验证安装成功:

    tsc -v  # 会显示 TS 版本号,如 Version 5.3.3
    

手动方式需要先编译ts文件,然后在执行运行代码,如:

tsc index.ts
node index.js

除了手动运行,还可以直接运行。在 VS Code 中直接运行 TypeScript 代码是一种高效的方式,无需手动编译步骤。以下是详细配置和使用方法:

步骤 1:初始化项目并安装依赖

  1. 打开终端(Ctrl+` 或 终端 > 新建终端)

  2. 执行以下命令:

# 初始化项目(生成 package.json)
npm init -y

# 安装必要依赖
npm install typescript ts-node @types/node --save-dev

步骤 2:创建 TypeScript 配置文件

在项目根目录创建 tsconfig.json

json

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "esModuleInterop": true,  // 解决 CommonJS 和 ES 模块兼容问题
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

步骤 3:配置 VS Code 运行方式

方式 A:使用 Code Runner 扩展(快速运行)

  1. 安装扩展:在 VS Code 扩展商店搜索并安装 Code Runner

  2. 配置 Code Runner:

    • 打开设置(Ctrl+,)
    • 搜索 code-runner.executorMap
    • 点击 "在 settings.json 中编辑"
    • 添加 TypeScript 配置:

    json

    "code-runner.executorMap": {
      "typescript": "npx ts-node"
    }
    
  3. 使用:打开 .ts 文件,右键选择 "Run Code" 或按 Ctrl+Alt+N

方式 B:配置调试环境(带断点调试)

  1. 在项目根目录创建 .vscode 文件夹

  2. 在 .vscode 中创建 launch.json 文件:

lanuch.json文件代码

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "ts-node 运行当前文件",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "npx",
      "runtimeArgs": ["ts-node", "${file}"],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen"
    }
  ]
}

  1. 使用:打开要运行的 .ts 文件,按 F5 启动调试,可使用断点、监视变量等功能

步骤 4:测试运行

创建一个测试文件 src/test.ts

typescript

function add(a: number, b: number): number {
  return a + b;
}

const result = add(2, 3);
console.log(`2 + 3 = ${result}`);

使用上述任一方式运行,终端会输出:2 + 3 = 5

常见问题解决

  1. 若出现 "Cannot use import statement outside a module" 错误:

    • 确保 tsconfig.json 中 module 设置为 CommonJS
    • 检查 package.json 中是否有 "type": "module",如有可暂时移除
  2. 版本兼容问题:

    bash

    # 更新依赖到最新版本
    npm update typescript ts-node
    
  3. 全局安装 ts-node(可选):

    bash

    npm install -g ts-node typescript
    # 之后可直接使用 ts-node 命令
    ts-node src/test.ts
    

通过以上配置,你可以在 VS Code 中便捷地运行和调试 TypeScript 代码,无需手动编译步骤,大幅提升开发效率。