跳到主要内容

TypeScript 环境配置

本章将介绍如何安装和配置 TypeScript 开发环境。

安装 TypeScript

使用 npm 安装

# 全局安装
npm install -g typescript

# 验证安装
tsc --version
# Version 5.x.x

# 本地安装(推荐)
npm install --save-dev typescript

解释:推荐在项目中本地安装 TypeScript,这样可以确保团队成员使用相同的版本。

使用 npx 运行

# 使用 npx 运行本地安装的 tsc
npx tsc --version

第一个 TypeScript 程序

创建文件

创建 hello.ts 文件:

// hello.ts
function greet(name: string): string {
return `Hello, ${name}!`;
}

const message = greet("TypeScript");
console.log(message);

编译运行

# 编译 TypeScript 文件
tsc hello.ts

# 运行生成的 JavaScript 文件
node hello.js
// 输出:Hello, TypeScript!

解释tsc 命令将 .ts 文件编译成 .js 文件。编译后的 JavaScript 文件可以在 Node.js 或浏览器中运行。

编译选项

# 指定输出目录
tsc hello.ts --outDir dist

# 指定目标版本
tsc hello.ts --target ES2020

# 监听文件变化
tsc hello.ts --watch

// 同时使用多个选项
tsc hello.ts --outDir dist --target ES2020 --watch

tsconfig.json 配置

创建配置文件

# 生成默认配置文件
tsc --init

常用配置选项

{
"compilerOptions": {
/* 基本选项 */
"target": "ES2020", // 编译目标版本
"module": "commonjs", // 模块系统
"outDir": "./dist", // 输出目录
"rootDir": "./src", // 源码目录
"strict": true, // 启用所有严格类型检查

/* 类型检查 */
"noImplicitAny": true, // 禁止隐式 any
"strictNullChecks": true, // 严格的 null 检查
"noUnusedLocals": true, // 检查未使用的变量
"noUnusedParameters": true, // 检查未使用的参数
"noImplicitReturns": true, // 检查每个分支都有返回值

/* 模块解析 */
"moduleResolution": "node", // 模块解析策略
"esModuleInterop": true, // 允许 default 导入
"allowSyntheticDefaultImports": true, // 允许合成默认导入

/* 其他 */
"sourceMap": true, // 生成 source map
"declaration": true, // 生成 .d.ts 声明文件
"removeComments": true // 移除注释
},
"include": ["src/**/*"], // 包含的文件
"exclude": ["node_modules", "dist"] // 排除的文件
}

解释

  • target 指定编译后的 JavaScript 版本,现代浏览器支持 ES2015+
  • strict 开启所有严格模式选项,推荐开启
  • sourceMap 生成映射文件,方便调试

使用配置文件编译

# 使用 tsconfig.json 配置编译
tsc

# 指定配置文件
tsc --project tsconfig.build.json

# 监听模式
tsc --watch

VS Code 配置

推荐扩展

  1. TypeScript Vue Plugin (Volar) - Vue 文件中的 TypeScript 支持
  2. ESLint - 代码检查
  3. Prettier - 代码格式化

settings.json 配置

{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
}
}

项目结构示例

my-typescript-project/
├── src/
│ ├── index.ts
│ ├── utils/
│ │ └── helpers.ts
│ └── types/
│ └── index.d.ts
├── dist/ # 编译输出目录
├── node_modules/
├── package.json
├── tsconfig.json
└── README.md

与构建工具集成

Webpack 集成

npm install --save-dev ts-loader typescript
// webpack.config.js
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.ts', '.js']
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};

Vite 集成

Vite 原生支持 TypeScript,无需额外配置:

# 创建 Vite + TypeScript 项目
npm create vite@latest my-app -- --template ts

ts-node 直接运行

ts-node 可以直接运行 TypeScript 代码,无需先编译:

# 安装
npm install --save-dev ts-node

# 运行 TypeScript 文件
npx ts-node src/index.ts

# 在 package.json 中添加脚本
{
"scripts": {
"dev": "ts-node src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}
}

解释ts-node 适合开发环境快速测试,生产环境仍需编译为 JavaScript。

类型声明文件

安装类型声明

# 安装 Node.js 类型声明
npm install --save-dev @types/node

# 安装其他库的类型声明
npm install --save-dev @types/lodash
npm install --save-dev @types/express

解释:许多第三方库的类型声明托管在 DefinitelyTyped 仓库中,通过 @types/ 包安装。

创建自定义声明文件

// src/types/custom.d.ts
declare module 'my-library' {
export function doSomething(value: string): number;
export interface Config {
timeout: number;
retries?: number;
}
}

常见问题

1. 类型错误但能运行

TypeScript 的类型检查在编译时进行,类型错误不会阻止 JavaScript 生成:

# 有错误时不生成输出文件
tsc --noEmitOnError

2. 第三方库没有类型

// 创建 declarations.d.ts
declare module 'untyped-library';

3. 配置不生效

确保在正确的目录运行 tsc,并且 tsconfig.json 在项目根目录。

小结

本章我们学习了:

  1. TypeScript 的安装方法
  2. 编译 TypeScript 文件
  3. tsconfig.json 配置选项
  4. VS Code 开发环境配置
  5. 与构建工具的集成
  6. 使用 ts-node 直接运行
  7. 类型声明文件的使用

练习

  1. 创建一个新的 TypeScript 项目
  2. 配置 tsconfig.json,开启严格模式
  3. 编写一个简单的 TypeScript 程序并编译运行