安装与快速开始
本章涵盖 TypeScript 开发环境搭建、三种编译运行方式对比、tsconfig 配置详解以及推荐的项目结构,帮助你从零启动第一个 TS 项目。
前置条件
- Node.js 18+ — TypeScript 编译器和工具链依赖 Node.js 运行时
- 包管理器:npm(随 Node.js 自带)、pnpm 或 yarn 任选其一
安装
全局安装 tsc 编译器后可在任意目录直接调用:
npm install -g typescript
tsc -v # 验证安装,输出版本号如 Version 5.x在项目中使用时,推荐作为本地开发依赖安装,锁定版本:
npm i -D typescript💡 最佳实践:优先使用项目本地依赖,避免全局版本与 CI/团队成员不一致。
第一个程序
创建 hello.ts,包含一个带类型注解的函数:
function greet(name: string): string {
return `Hello, ${name}!`
}
console.log(greet("TypeScript"))编译并执行:
tsc hello.ts // ✅ 生成 hello.js
node hello.js // ✅ 输出: Hello, TypeScript!编译方式对比
| 方式 | 特点 | 适用场景 |
|---|---|---|
tsc |
编译为 JS 后执行,输出纯 JS 文件 | 生产构建 |
ts-node |
直接运行 TS 文件,内置 JIT 编译 | 开发/脚本 |
tsx |
基于 esbuild,速度最快,支持 ESM/CJS | 开发/脚本(推荐) |
npm i -D tsx
npx tsx hello.ts // ✅ 直接输出: Hello, TypeScript!⚡ 性能提示:
tsx使用 esbuild 进行转译,不执行类型检查,因此比ts-node快 10-30 倍。开发时用tsx运行代码,配合tsc --noEmit做类型检查。
tsconfig 配置
使用 tsc --init 生成带有所有选项(已注释)的配置文件:
tsc --init核心配置速查
| 配置 | 说明 |
|---|---|
target |
编译目标 JS 版本(ESNext / ES2022 等) |
module |
模块系统(ESNext / NodeNext / CommonJS) |
moduleResolution |
模块解析策略(bundler / node / node16) |
strict |
开启所有严格类型检查(推荐) |
outDir |
编译输出目录 |
rootDir |
源码根目录 |
sourceMap |
生成 .js.map 映射文件,方便调试 |
noEmitOnError |
编译出错时不生成文件 |
noUnusedLocals |
未使用的局部变量报错 |
noUnusedParameters |
未使用的函数参数报错 |
noImplicitReturns |
函数缺少返回值时报错 |
esModuleInterop |
允许 default import 导入 CJS 模块 |
skipLibCheck |
跳过 .d.ts 类型检查,加速编译 |
forceConsistentCasingInFileNames |
文件名大小写需与 import 一致 |
完整示例
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"rootDir": "./src",
"outDir": "./dist",
"sourceMap": true,
"noEmitOnError": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}🚨 陷阱:
skipLibCheck: true会跳过第三方.d.ts的类型检查,能显著加速编译,但也可能掩盖类型冲突。若遇到诡异类型报错,可临时关闭该选项排查。
💡 最佳实践:始终开启
strict: true。它聚合了noImplicitAny、strictNullChecks、strictFunctionTypes等多个子选项,能在开发阶段捕获大量潜在 bug。
监听模式
tsc -w(watch 模式)会在文件变更时自动重新编译:
tsc -w # 监听 tsconfig.json 所在项目
tsc main.ts -w # 监听单个文件(忽略 tsconfig.json)常用于配合 nodemon 实现自动重启:
npx nodemon --watch src --ext ts --exec "tsx src/index.ts"项目结构推荐
my-project/
├── src/
│ ├── index.ts
│ ├── types/
│ │ └── index.ts
│ └── utils/
│ └── helpers.ts
├── dist/ # 编译输出(由 tsc 生成)
├── node_modules/
├── tsconfig.json
└── package.jsonsrc/types/ 放置接口与类型定义,src/utils/ 放置通用工具函数,业务代码可按功能模块进一步划分子目录。
快速检查清单
- Node.js 18+ 已安装
-
tsc -v正常输出版本号 -
tsconfig.json已配置strict: true -
src目录结构已创建 - 第一个
.ts文件编译成功
参考:TypeScript 官方文档 https://www.typescriptlang.org/docs/