TypeScript安装与配置 #

一、安装TypeScript #

1.1 使用npm安装 #

最常见的方式是通过npm(Node.js包管理器)安装TypeScript:

bash
npm install -g typescript

安装完成后,可以验证安装:

bash
tsc --version

输出类似:

text
Version 5.4.2

1.2 使用yarn安装 #

如果你使用yarn作为包管理器:

bash
yarn global add typescript

1.3 使用pnpm安装 #

如果你使用pnpm:

bash
pnpm add -g typescript

1.4 本地安装(推荐) #

在项目中本地安装TypeScript:

bash
npm install typescript --save-dev

或:

bash
yarn add typescript --dev

本地安装后,可以通过npx运行:

bash
npx tsc --version

1.5 使用安装包安装 #

TypeScript官网下载安装包进行安装。

二、TypeScript编译器(tsc) #

2.1 编译单个文件 #

创建一个简单的TypeScript文件hello.ts

typescript
const message: string = 'Hello, TypeScript!';
console.log(message);

使用tsc编译:

bash
tsc hello.ts

这将生成hello.js文件。

2.2 监听模式 #

使用--watch-w参数监听文件变化:

bash
tsc hello.ts --watch

2.3 常用编译选项 #

选项 说明
--outDir 指定输出目录
--target 指定ECMAScript目标版本
--module 指定模块系统
--strict 启用所有严格类型检查选项
--watch 监听文件变化
--help 显示帮助信息
bash
tsc hello.ts --outDir dist --target ES2020 --strict

三、tsconfig.json配置文件 #

3.1 创建配置文件 #

使用tsc --init创建默认配置文件:

bash
tsc --init

这将生成tsconfig.json文件。

3.2 基本配置结构 #

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

3.3 常用配置选项详解 #

target #

指定编译后的JavaScript版本:

json
{
  "compilerOptions": {
    "target": "ES2020"
  }
}

可选值:ES3ES5ES6/ES2015ES2016ES2022ESNext

module #

指定模块系统:

json
{
  "compilerOptions": {
    "module": "commonjs"
  }
}

可选值:commonjsamdsystemumdes6/ES2015ES2020ESNextNone

outDir和rootDir #

json
{
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src"
  }
}
  • outDir:编译输出目录
  • rootDir:源代码根目录

strict #

启用所有严格类型检查选项:

json
{
  "compilerOptions": {
    "strict": true
  }
}

等同于启用以下所有选项:

  • --strictNullChecks
  • --strictFunctionTypes
  • --strictBindCallApply
  • --strictPropertyInitialization
  • --noImplicitThis
  • --alwaysStrict

esModuleInterop #

启用ES模块互操作性:

json
{
  "compilerOptions": {
    "esModuleInterop": true
  }
}

允许使用CommonJS模块的默认导入:

typescript
import React from 'react';

sourceMap #

生成Source Map文件:

json
{
  "compilerOptions": {
    "sourceMap": true
  }
}

lib #

指定编译时包含的库文件:

json
{
  "compilerOptions": {
    "lib": ["ES2020", "DOM"]
  }
}

moduleResolution #

指定模块解析策略:

json
{
  "compilerOptions": {
    "moduleResolution": "node"
  }
}

可选值:node(Node.js风格)、classic(TypeScript经典风格)

baseUrl和paths #

配置路径别名:

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

使用:

typescript
import { Button } from '@components/Button';

3.4 include和exclude #

json
{
  "include": [
    "src/**/*",
    "tests/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "**/*.test.ts"
  ]
}

四、开发环境配置 #

4.1 VSCode配置 #

VSCode内置TypeScript支持,推荐安装以下扩展:

  • TypeScript Importer:自动导入
  • Move TS:移动文件时自动更新导入路径

工作区设置 #

创建.vscode/settings.json

json
{
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true,
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

4.2 配置ESLint #

安装依赖:

bash
npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

创建.eslintrc.js

javascript
module.exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended'
  ],
  rules: {
    '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
    '@typescript-eslint/explicit-function-return-type': 'off'
  }
};

4.3 配置Prettier #

安装依赖:

bash
npm install --save-dev prettier

创建.prettierrc

json
{
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5",
  "printWidth": 100
}

五、项目结构示例 #

5.1 基本项目结构 #

text
my-typescript-project/
├── src/
│   ├── index.ts
│   ├── utils/
│   │   └── helpers.ts
│   └── types/
│       └── index.ts
├── dist/
├── node_modules/
├── package.json
├── tsconfig.json
├── .eslintrc.js
├── .prettierrc
└── .gitignore

5.2 package.json配置 #

json
{
  "name": "my-typescript-project",
  "version": "1.0.0",
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "dev": "tsc --watch",
    "lint": "eslint src/**/*.ts",
    "format": "prettier --write src/**/*.ts"
  },
  "devDependencies": {
    "typescript": "^5.4.2",
    "@typescript-eslint/parser": "^7.0.0",
    "@typescript-eslint/eslint-plugin": "^7.0.0",
    "eslint": "^8.57.0",
    "prettier": "^3.2.0"
  }
}

六、编译和运行 #

6.1 编译项目 #

bash
npm run build

或直接运行:

bash
tsc

6.2 运行编译后的代码 #

bash
node dist/index.js

6.3 使用ts-node直接运行 #

安装ts-node:

bash
npm install --save-dev ts-node

直接运行TypeScript:

bash
npx ts-node src/index.ts

6.4 使用tsx运行 #

tsx是更快的TypeScript运行器:

bash
npm install --save-dev tsx

运行:

bash
npx tsx src/index.ts

七、常见问题 #

7.1 找不到模块 #

确保安装了类型定义:

bash
npm install --save-dev @types/node

7.2 类型定义缺失 #

对于没有类型定义的库,可以:

  1. 安装@types/包名
  2. 创建自定义声明文件
typescript
declare module 'some-library' {
  export function someFunction(arg: string): number;
}

7.3 编译速度慢 #

使用增量编译:

json
{
  "compilerOptions": {
    "incremental": true
  }
}

八、总结 #

本章介绍了TypeScript的安装和配置:

  1. 安装方式:npm、yarn、pnpm全局或本地安装
  2. 编译器使用:tsc命令和常用选项
  3. 配置文件:tsconfig.json详解
  4. 开发环境:VSCode、ESLint、Prettier配置
  5. 项目结构:推荐的项目组织方式
  6. 编译运行:多种运行TypeScript的方式

准备好开始编写第一个TypeScript程序了吗?让我们进入下一章。

最后更新:2026-03-26