开发环境搭建

开始 TypeScript 开发前,需要搭建合适的开发环境。本文介绍几种常见的方式。

安装 Node.js

TypeScript 编译器基于 Node.js 运行,首先需要安装 Node.js。

访问 Node.js 官网 下载并安装 LTS 版本。

验证安装:

node -v
npm -v

安装 TypeScript 编译器

全局安装

npm install -g typescript

验证安装:

tsc -v

项目本地安装

推荐在项目中本地安装:

npm init -y
npm install typescript --save-dev

使用 npx 运行:

npx tsc -v

编辑器配置

VS Code

VS Code 对 TypeScript 有原生支持,推荐安装以下扩展:

  • TypeScript Hero:代码组织工具
  • TSLintESLint:代码检查

WebStorm

WebStorm 内置 TypeScript 支持,无需额外配置。

其他编辑器

编辑器TypeScript 支持
Sublime Text需安装插件
Vim需配置 coc.nvim
Atom需安装 atom-typescript

创建项目

方式一:手动创建

mkdir my-ts-project
cd my-ts-project
npm init -y
npm install typescript --save-dev
npx tsc --init

这会生成 tsconfig.json 配置文件。

方式二:使用脚手架

# Vite + TypeScript
npm create vite@latest my-project -- --template vanilla-ts

# Create React App
npx create-react-app my-app --template typescript

# Vue 3 + TypeScript
npm create vue@latest

tsconfig.json 配置

基础配置示例:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "lib": ["ES2020", "DOM"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

常用选项说明

选项说明
target编译目标 ES 版本
module模块系统类型
outDir输出目录
rootDir源码目录
strict启用严格模式
sourceMap生成 source map

编译与运行

手动编译

npx tsc

编译后生成 JavaScript 文件:

src/
  index.ts    → dist/
                 index.js

使用 ts-node 直接运行

开发时可以直接运行 TypeScript:

npm install -D ts-node
npx ts-node src/index.ts

使用 nodemon 自动重载

npm install -D nodemon ts-node

# package.json
{
  "scripts": {
    "dev": "nodemon --exec ts-node src/index.ts"
  }
}

项目结构

推荐的项目结构:

my-project/
├── src/
│   ├── index.ts
│   ├── utils/
│   │   └── helper.ts
│   └── types/
│       └── index.ts
├── dist/
├── node_modules/
├── package.json
└── tsconfig.json

配置 npm scripts

{
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "dev": "ts-node src/index.ts",
    "watch": "tsc -w"
  }
}

常见问题

找不到模块

安装对应的类型定义:

npm install -D @types/node
npm install -D @types/lodash

编译报错但想运行

临时关闭严格模式:

{
  "compilerOptions": {
    "strict": false,
    "noImplicitAny": false
  }
}

路径别名不生效

配置路径映射:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}