开始 TypeScript 开发前,需要搭建合适的开发环境。本文介绍几种常见的方式。
TypeScript 编译器基于 Node.js 运行,首先需要安装 Node.js。
访问 Node.js 官网 下载并安装 LTS 版本。
验证安装:
node -v
npm -v
npm install -g typescript
验证安装:
tsc -v
推荐在项目中本地安装:
npm init -y
npm install typescript --save-dev
使用 npx 运行:
npx tsc -v
VS Code 对 TypeScript 有原生支持,推荐安装以下扩展:
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
基础配置示例:
{
"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
开发时可以直接运行 TypeScript:
npm install -D ts-node
npx ts-node src/index.ts
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
{
"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/*"]
}
}
}