Skip to content
On this page

TypeScript 工具与生态系统

TypeScript 拥有丰富的工具生态系统,这些工具能够显著提升开发效率和代码质量。

核心工具

TypeScript 编译器 (tsc)

TypeScript 编译器是整个生态系统的核心,负责将 TypeScript 代码编译为 JavaScript。

bash
# 基本编译
tsc

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

# 编译特定文件
tsc src/main.ts

# 监视模式
tsc --watch

# 指定输出目录
tsc --outDir dist

# 指定目标版本
tsc --target ES2020

# 启用严格模式
tsc --strict

TypeScript 语言服务 (TypeScript Language Service)

TypeScript 语言服务为编辑器提供智能感知功能:

json
// tsconfig.json
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "typescript-deno-plugin",
        "enable": true
      }
    ]
  }
}

开发工具

TypeScript Node (ts-node)

ts-node 允许直接运行 TypeScript 文件,无需预编译。

bash
# 安装
npm install -g ts-node

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

# 在 REPL 中使用
ts-node

# 与 nodemon 结合实现热重载
npx nodemon --exec ts-node src/index.ts

TypeScript ESLint

TypeScript ESLint 提供了对 TypeScript 代码的静态分析。

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

# .eslintrc.js
module.exports = {
  parser: '@typescript-eslint/parser',
  plugins: [
    '@typescript-eslint',
  ],
  extends: [
    'eslint:recommended',
    '@typescript-eslint/recommended',
  ],
  rules: {
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-parameter-properties': 'off',
    '@typescript-eslint/no-use-before-define': 'off',
    'prefer-template': 'error',
    '@typescript-eslint/no-var-requires': 'off',
    '@typescript-eslint/no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^_',
        varsIgnorePattern: '^_',
        caughtErrorsIgnorePattern: '^_',
      },
    ],
  },
};

Prettier 与 TypeScript

Prettier 提供代码格式化功能,与 TypeScript 完美集成。

bash
# 安装
npm install --save-dev prettier

# .prettierrc
{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2
}

# .prettierignore
node_modules/
dist/
build/

Jest 与 TypeScript

Jest 是流行的 JavaScript 测试框架,与 TypeScript 结合使用。

bash
# 安装
npm install --save-dev jest @types/jest ts-jest

# jest.config.js
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  roots: ['<rootDir>/src'],
  testMatch: ['**/__tests__/**/*.+(ts|tsx|js)', '**/?(*.)+(spec|test).+(ts|tsx|js)'],
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest',
  },
};

构建工具集成

Webpack 与 TypeScript

javascript
// webpack.config.js
const path = require('path');

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

Rollup 与 TypeScript

javascript
// rollup.config.js
import typescript from '@rollup/plugin-typescript';

export default {
  input: 'src/main.ts',
  output: {
    dir: 'dist',
    format: 'cjs'
  },
  plugins: [
    typescript({ tsconfig: './tsconfig.json' })
  ]
};

Vite 与 TypeScript

javascript
// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    lib: {
      entry: './src/index.ts',
      name: 'MyLib',
      fileName: 'my-lib'
    },
    rollupOptions: {
      external: ['vue'],
      output: {
        globals: {
          vue: 'Vue'
        }
      }
    }
  }
})

代码生成工具

TypeDoc

TypeDoc 从 TypeScript 源代码生成文档。

bash
# 安装
npm install --save-dev typedoc

# 生成文档
npx typedoc src/

# 配置文件 typedoc.json
{
  "entryPoints": ["src/index.ts"],
  "out": "docs/api",
  "excludeNotExported": true,
  "theme": "default"
}

GraphQL Code Generator

GraphQL Code Generator 可以为 GraphQL 操作和模式生成 TypeScript 类型。

yaml
# codegen.yml
overwrite: true
schema: "http://localhost:3000/graphql"
documents: "src/**/*.graphql"
generates:
  src/generated/graphql.ts:
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-react-apollo"

类型定义管理

DefinitelyTyped

DefinitelyTyped 是 TypeScript 类型定义的中央存储库。

bash
# 安装类型定义
npm install --save-dev @types/node
npm install --save-dev @types/react
npm install --save-dev @types/jest

自定义类型声明

typescript
// src/types/index.d.ts
declare module "*.json" {
  const value: any;
  export default value;
}

declare module "*.svg" {
  const content: string;
  export default content;
}

// 全局变量声明
declare global {
  interface Window {
    myCustomProperty: string;
  }
}

调试工具

Source Maps

TypeScript 支持生成 source maps 以便在浏览器中调试。

json
// tsconfig.json
{
  "compilerOptions": {
    "sourceMap": true,
    "inlineSourceMap": false,
    "sourceRoot": "/",
    "mapRoot": "/"
  }
}

调试配置

json
// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug TypeScript",
      "runtimeArgs": ["-r", "ts-node/register"],
      "args": ["${workspaceFolder}/src/index.ts"],
      "env": {
        "TS_NODE_PROJECT": "${workspaceFolder}/tsconfig.json"
      }
    }
  ]
}

性能工具

TypeScript 编译性能

json
// tsconfig.json - 性能优化配置
{
  "compilerOptions": {
    "incremental": true,
    "tsBuildInfoFile": ".tsbuildinfo",
    "composite": true,
    "declaration": true,
    "declarationMap": true
  }
}

编译时间分析

bash
# 分析编译性能
tsc --generateCpuProfile compilation.cpuprofile

# 详细编译信息
tsc --extendedDiagnostics

依赖管理工具

Depcheck

检测未使用的依赖。

bash
# 安装
npm install -g depcheck

# 检查项目依赖
depcheck

Typesync

自动安装缺失的类型定义。

bash
# 安装
npm install -g typesync

# 同步类型定义
typesync

代码质量工具

Type-coverage

检查类型覆盖率。

bash
# 安装
npm install --save-dev type-coverage

# 检查类型覆盖率
npx type-coverage

# package.json 脚本
{
  "scripts": {
    "type-check": "tsc --noEmit",
    "type-coverage": "type-coverage --detail --at-least 95"
  }
}

Ts-morph

用于分析和修改 TypeScript 代码的工具。

typescript
import { Project } from "ts-morph";

const project = new Project();
const sourceFile = project.addSourceFileAtPath("src/example.ts");

// 分析代码结构
const classes = sourceFile.getClasses();
const functions = sourceFile.getFunctions();

console.log(`Found ${classes.length} classes and ${functions.length} functions`);

框架特定工具

Angular CLI

Angular 的官方工具链,深度集成 TypeScript。

bash
# 创建新项目
ng new my-app

# 生成组件
ng generate component my-component

# 构建项目
ng build --prod

NestJS CLI

NestJS 框架的命令行工具。

bash
# 安装
npm install -g @nestjs/cli

# 创建新项目
nest new my-project

# 生成模块
nest generate module users

# 生成服务
nest generate service users

代码转换工具

Babel 与 TypeScript

虽然 TypeScript 编译器可以处理转换,但 Babel 也可以用于 TypeScript。

bash
# 安装
npm install --save-dev @babel/core @babel/preset-typescript

# babel.config.json
{
  "presets": ["@babel/preset-typescript"]
}

SWC (Speedy Web Compiler)

更快的 TypeScript 编译器替代方案。

bash
# 安装
npm install --save-dev @swc/core

# .swcrc
{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": true
    }
  }
}

项目结构工具

Lerna

用于管理多包存储库的工具。

json
// lerna.json
{
  "packages": [
    "packages/*"
  ],
  "version": "independent"
}
bash
# 引导多包项目
lerna bootstrap

# 构建所有包
lerna run build

小结

TypeScript 的工具生态系统非常丰富,涵盖了开发、构建、测试、文档生成等各个方面。合理选择和配置这些工具可以显著提升开发效率和代码质量。根据项目需求选择合适的工具组合,并建立规范的开发流程是成功使用 TypeScript 的关键。