Skip to content
第 92 / 250 章前端⏱ 10 分钟阅读

第 92 章:TypeScript 开发环境搭建

学习目标

  • 安装 Node.js 与 TypeScript 编译器
  • 理解 npm/pnpm 包管理工具
  • 搭建 VS Code + TypeScript 高效开发环境
  • 完成第一个 TS 项目的目录规范

一、Node.js:TS 编译器的运行环境

TypeScript 编译器(tsc)是用 Node.js 写的,所以先要装 Node.js。

1.1 安装 Node.js

bash
# 推荐用 nvm 管理多版本(macOS/Linux)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
nvm install 18
nvm use 18

# Windows 直接下载安装包
# https://nodejs.org/zh-cn/download/releases
# 推荐 LTS 版本(18 / 20 / 22)

# 验证
node -v    # v18.19.0 或更新
npm -v     # 9.x 或更新

1.2 为什么要 LTS 版本?

企业级开发原则:永远用 LTS 版本,避免线上因 Node 版本 bug 翻车。

1.3 包管理器选择

bash
# npm(Node 自带,无需安装)
npm install -D typescript

# pnpm(推荐,更快、磁盘更省)
npm install -g pnpm
pnpm add -D typescript

# yarn(历史遗留项目)
npm install -g yarn
yarn add -D typescript
工具优点缺点
npm内置、兼容性好慢、嵌套 node_modules
pnpm快、扁平、节省磁盘Windows 偶尔遇到软链问题
yarn兼容性中等已被 pnpm 超越

本教程统一用 pnpm

二、安装 TypeScript

2.1 全局安装(用于快速试验)

bash
# 全局安装 tsc 命令
npm install -g typescript

# 验证
tsc -v
# Version 5.6.0

适用场景:临时跑 .ts 文件测试、学习目的。

2.2 项目本地安装(推荐)

bash
# 创建项目目录
mkdir hello-typescript && cd hello-typescript

# 初始化项目
pnpm init              # 生成 package.json

# 安装 TypeScript 为开发依赖
pnpm add -D typescript  # 写入 package.json 的 devDependencies

# 验证
pnpm tsc -v
# Version 5.6.0

为什么推荐本地安装? 不同项目用不同 TS 版本,全局会冲突;CI/CD 和同事克隆项目时,TS 版本通过 package.json 锁定。

2.3 编译第一个 TS 文件

bash
# 创建 hello.ts
echo "const greet = (name: string) => console.log(\`Hello, \${name}!\`);" > hello.ts
echo "greet('TypeScript');" >> hello.ts

# 编译
pnpm tsc hello.ts

# 生成 hello.js(同时还有 hello.js.map 映射文件)
node hello.js
# Hello, TypeScript!

三、tsconfig.json:TS 项目的"宪法"

tsconfig.json 控制 TS 编译器的所有行为。

3.1 初始化

bash
pnpm tsc --init
# 生成一份带默认注释的 tsconfig.json(60+ 行选项全部列出来)

3.2 企业级推荐配置

json
{
  "compilerOptions": {
    /* ① 目标与模块 */
    "target": "ES2020",              // 编译到 ES2020(Node 14/现代浏览器都支持)
    "module": "ESNext",              // 模块系统用 ES Module(import/export)
    "lib": ["ES2020", "DOM"],        // 可用 API:ES2020 + 浏览器 DOM
    "moduleResolution": "node",      // 模块解析方式

    /* ② 严格模式(强烈建议全开)*/
    "strict": true,                  // 开启所有严格选项
    "noImplicitAny": true,           // 禁止隐式 any
    "strictNullChecks": true,        // 严格的 null/undefined 检查
    "noUnusedLocals": true,          // 未使用的变量报错
    "noUnusedParameters": true,      // 未使用的参数报错
    "noFallthroughCasesInSwitch": true, // switch 必须有 break/return

    /* ③ 输出 */
    "outDir": "./dist",              // 编译产物输出目录
    "rootDir": "./src",              // 源码根目录
    "sourceMap": true,               // 生成 .map 文件,方便调试

    /* ④ 互操作性 */
    "esModuleInterop": true,         // 允许 import default from 'xxx'
    "forceConsistentCasingInFileNames": true, // 文件名大小写必须一致(Linux 兼容)

    /* ⑤ 跳过检查 */
    "skipLibCheck": true             // 跳过 node_modules 里的 .d.ts 检查(提速)
  },
  "include": ["src/**/*"],           // 编译哪些文件
  "exclude": ["node_modules", "dist"] // 排除
}

3.3 关键选项详解

最关键的 3 个开关

选项推荐值作用
stricttrue严格模式大礼包,推荐全开
targetES2020兼容 Node 14+ / 现代浏览器
moduleESNext现代项目首选 ES Module

四、VS Code 配置(最佳拍档)

VS Code 对 TypeScript 的支持是开箱即用的。

4.1 为什么 VS Code + TS 是绝配

VS Code 内部自带 TS 编译器(自带 tsc),不用装任何插件就能:

  • ✅ 实时类型检查(波浪线)
  • ✅ 智能补全
  • ✅ 重命名符号(F2
  • ✅ 跳转到定义(F12
  • ✅ 查看类型(Ctrl+K Ctrl+T

4.2 推荐插件

插件作用
Error Lens把错误信息直接放大显示在代码旁边
Pretty TypeScript Errors把难懂的 TS 错误翻译成大白话
Todo Tree高亮 // TODO 注释
Path Intellisense文件路径自动补全
ESLint代码风格检查
Prettier代码格式化

4.3 VS Code 工作区配置

在项目根目录创建 .vscode/settings.json

json
{
  "editor.formatOnSave": true,                  // 保存时格式化
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "typescript.tsdk": "node_modules/typescript/lib", // 用项目本地 TS
  "typescript.enablePromptUseWorkspaceTsdk": true,
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

为什么 typescript.tsdk 要指向项目本地? 让 VS Code 用项目锁定的 TS 版本,避免编辑器版本和编译器版本不一致。

五、完整项目结构

hello-typescript/
├── src/                    # 源码
│   ├── index.ts            # 入口
│   ├── utils.ts
│   └── types.ts
├── dist/                   # 编译产物(.gitignore)
├── node_modules/           # 依赖
├── .vscode/
│   └── settings.json
├── .gitignore
├── tsconfig.json
├── package.json
└── README.md

5.1 完整 package.json

json
{
  "name": "hello-typescript",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "build": "tsc",
    "dev": "tsc --watch",           // 监听文件变化自动编译
    "type-check": "tsc --noEmit",   // 只检查类型不输出文件
    "clean": "rm -rf dist"
  },
  "devDependencies": {
    "typescript": "^5.6.0",
    "@types/node": "^22.0.0"
  }
}

5.2 .gitignore

gitignore
node_modules/
dist/
*.log
.DS_Store
.vscode/*
!.vscode/settings.json

六、第一个完整项目

6.1 编写代码

typescript
// src/types.ts
export interface User {
  id: number;
  name: string;
  email: string;
  createdAt: Date;
}

export type UserRole = 'admin' | 'user' | 'guest';
typescript
// src/utils.ts
import type { User, UserRole } from './types.js';

export function createUser(name: string, email: string, role: UserRole = 'user'): User {
  return {
    id: Date.now(),
    name,
    email,
    createdAt: new Date()
  };
}

export function greet(user: User): string {
  return `Hello, ${user.name}! You are a ${user.role ?? 'user'}.`;
}
typescript
// src/index.ts
import { createUser, greet } from './utils.js';
import type { User } from './types.js';

const u: User = createUser('Tom', 'tom@example.com');
console.log(greet(u));

6.2 编译与运行

bash
pnpm tsc         # 编译 src/ 到 dist/
node dist/index.js
# Hello, Tom! You are a user.

6.3 监听模式(开发体验)

bash
pnpm tsc --watch
# 改代码自动编译,省去手动跑 tsc

七、常见问题

7.1 找不到模块 './types.js'

typescript
// ❌ 报错
import type { User } from './types';

// ✅ 正确(ES Module 必须写扩展名)
import type { User } from './types.js';

为什么? ES Module 规范要求路径必须带扩展名。TS 编译后会保留 .js 后缀。

7.2 全局 TS 和项目 TS 版本冲突

bash
# 查看当前用的是哪个
pnpm tsc -v
# 或
npx tsc -v

# 强制用项目版本
pnpm exec tsc --build

7.3 类型不识别("Cannot find name 'console'")

json
// tsconfig.json
{
  "compilerOptions": {
    "lib": ["ES2020"]  // 加上 DOM 也能用 console
  }
}

八、本章小结

要点关键
Node.jsLTS 版本(18/20/22),用 nvm/fnm 管理
TS 安装项目本地安装:pnpm add -D typescript
tsconfigstrict: true + target: ES2020 + module: ESNext
VS Code内置 TS 最佳拍档,配 tsdk 指向项目本地
项目结构src/ + dist/ + tsconfig.json + package.json

动手练习

  1. 环境搭建:按本章步骤搭一个 hello-typescript 项目,运行通第 6 节的示例
  2. 配置探索:把 strict 设为 false,看看会冒出哪些警告;再设回 true,对比差别
  3. VS Code 体验:装上 Error Lens 插件,对比类型错误的提示效果

推荐阅读


下一章第 93 章:第一个 TypeScript 程序

本站基于 VitePress 构建 · 由 Codebook 团队维护