手动方式需要先编译ts文件,然后在执行运行代码,如:
bash
tsc index.ts
node index.js
除了手动运行,还可以直接运行。在 VS Code 中直接运行 TypeScript 代码是一种高效的方式,无需手动编译步骤。以下是详细配置和使用方法:
步骤 1:初始化项目并安装依赖
-
打开终端(Ctrl+` 或 终端 > 新建终端)
-
执行以下命令:
bash
# 初始化项目(生成 package.json)
npm init -y
# 安装必要依赖
npm install typescript ts-node @types/node --save-dev
步骤 2:创建 TypeScript 配置文件
在项目根目录创建 tsconfig.json
:
json
json
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"esModuleInterop": true, // 解决 CommonJS 和 ES 模块兼容问题
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
步骤 3:配置 VS Code 运行方式
方式 A:使用 Code Runner 扩展(快速运行)
-
安装扩展:在 VS Code 扩展商店搜索并安装 Code Runner
-
配置 Code Runner:
- 打开设置(Ctrl+,)
- 搜索
code-runner.executorMap
- 点击 "在 settings.json 中编辑"
- 添加 TypeScript 配置:
json
css"code-runner.executorMap": { "typescript": "npx ts-node" }
-
使用:打开
.ts
文件,右键选择 "Run Code" 或按 Ctrl+Alt+N
方式 B:配置调试环境(带断点调试)
-
在项目根目录创建
.vscode
文件夹 -
在
.vscode
中创建launch.json
文件:
lanuch.json文件代码
json
{
"version": "0.2.0",
"configurations": [
{
"name": "ts-node 运行当前文件",
"type": "node",
"request": "launch",
"runtimeExecutable": "npx",
"runtimeArgs": ["ts-node", "${file}"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}
- 使用:打开要运行的
.ts
文件,按 F5 启动调试,可使用断点、监视变量等功能
步骤 4:测试运行
创建一个测试文件 src/test.ts
:
typescript
typescript
function add(a: number, b: number): number {
return a + b;
}
const result = add(2, 3);
console.log(`2 + 3 = ${result}`);
使用上述任一方式运行,终端会输出:2 + 3 = 5
常见问题解决
-
若出现 "Cannot use import statement outside a module" 错误:
- 确保
tsconfig.json
中module
设置为CommonJS
- 检查
package.json
中是否有"type": "module"
,如有可暂时移除
- 确保
-
版本兼容问题:
bash
bash# 更新依赖到最新版本 npm update typescript ts-node
-
全局安装
ts-node
(可选):bash
bashnpm install -g ts-node typescript # 之后可直接使用 ts-node 命令 ts-node src/test.ts
通过以上配置,你可以在 VS Code 中便捷地运行和调试 TypeScript 代码,无需手动编译步骤,大幅提升开发效率。