安装typescript编译器需运行npm install -g typescript以支持tsc命令;2. 使用tsc --init生成tsconfig.json并配置compileroptions和include以定义编译行为和文件范围;3. vscode内置typescript支持,可安装官方插件增强体验;4. 编写typescript代码后运行tsc命令编译为javascript并输出到指定目录;5. 通过node dist/index.js运行编译后的文件;6. 解决vscode报错而命令行正常的问题需统一typescript版本,选择“use workspace version”并安装本地typescript;7. include指定要编译的文件如"src/*/",exclude排除如"node_modules"以提升编译效率;8. 配置自动编译需创建tasks.json并添加"watch": true,使保存时自动触发编译任务,从而提升开发效率。

VSCode配置TypeScript开发环境其实不难,简单来说就是安装必要的插件,配置tsconfig.json,然后就可以愉快地写代码了。下面详细说说步骤,以及一些踩坑经验。
安装好VSCode之后,就可以开始配置了。
安装TypeScript编译器: 全局安装TypeScript编译器是基础。打开你的终端,运行
npm install -g typescript
tsc
创建tsconfig.json文件: 在你的项目根目录下,创建一个
tsconfig.json
tsc --init
一个基本的
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"src/**/*"
]
}这里,
target
module
outDir
strict
include
安装VSCode的TypeScript插件: VSCode自带了对TypeScript的支持,但安装官方的TypeScript插件可以提供更好的开发体验。在VSCode的扩展商店搜索“TypeScript”,安装Microsoft提供的TypeScript Language Basics。
编写TypeScript代码: 在
src
index.ts
function greet(name: string) {
console.log(`Hello, ${name}!`);
}
greet("World");编译TypeScript代码: 在终端中运行
tsc
tsconfig.json
src
dist
运行JavaScript代码: 使用Node.js运行编译后的JavaScript文件。在终端中运行
node dist/index.js
有时候,VSCode可能会报一些TypeScript的错误,但你在命令行中使用
tsc
解决这个问题,首先确认VSCode使用的TypeScript版本。在VSCode中,打开一个TypeScript文件,点击右下角的TypeScript版本号,选择“Select TypeScript Version”。然后,选择“Use Workspace Version”。这会告诉VSCode使用项目中的TypeScript版本。
如果你的项目中没有安装TypeScript,可以使用
npm install --save-dev typescript
include
exclude
include
exclude
一个常见的用法是,使用
include
src
exclude
node_modules
{
"compilerOptions": {
// ...
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}include
exclude
*
?
**
正确配置
include
exclude
VSCode可以配置自动编译功能,这样每次保存TypeScript文件时,都会自动编译成JavaScript文件。
要配置自动编译,首先确保你已经安装了TypeScript编译器,并且创建了
tsconfig.json
Ctrl+Shift+B
Cmd+Shift+B
选择“tsc: build - tsconfig.json”。这会创建一个
.vscode/tasks.json
修改
.vscode/tasks.json
"watch": true
{
"version": "2.0.0",
"tasks": [
{
"type": "typescript",
"tsconfig": "tsconfig.json",
"problemMatcher": [
"$tsc"
],
"group": {
"kind": "build",
"isDefault": true
},
"watch": true
}
]
}保存
.vscode/tasks.json
自动编译功能可以大大提高开发效率,让你专注于编写代码,而不用手动运行
tsc
以上就是VSCode如何配置TypeScript开发环境 VSCode搭建TS项目的详细教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号