在 VS Code 中使用 TypeScript 进行开发和打包的几种方法

在 Visual Studio Code (VSCode) 中高效使用 TypeScript 进行开发和打包,需要结合合理的配置、工具链和开发流程。以下是详细步骤和最佳实践:


1. 环境准备

1.1 安装必要工具
  • Node.js 和 npm: TypeScript 需要 Node.js 环境。建议安装 LTS 版本。

    复制代码
    # 验证安装
    node -v
    npm -v
  • TypeScript 全局安装(可选):

    复制代码
    npm install -g typescript
1.2 VSCode 扩展

安装以下扩展提升开发效率:


2. 初始化 TypeScript 项目

2.1 创建项目
复制代码
mkdir my-ts-project
cd my-ts-project
npm init -y
2.2 安装 TypeScript
复制代码
npm install typescript @types/node --save-dev
2.3 生成 tsconfig.json
复制代码
npx tsc --init

修改 tsconfig.json(关键配置):

复制代码
{
  "compilerOptions": {
    "target": "ES2020",       // 编译目标版本
    "module": "CommonJS",     // 模块系统
    "outDir": "./dist",       // 输出目录
    "rootDir": "./src",       // 源码目录
    "strict": true,           // 启用严格类型检查
    "esModuleInterop": true,  // 兼容 CommonJS/ESM
    "sourceMap": true,        // 生成 SourceMap(调试必需)
    "skipLibCheck": true      // 跳过库类型检查(提升速度)
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

3. 开发环境配置

3.1 实时编译与监听

使用 TypeScript 的 --watch 模式自动编译:

复制代码
npx tsc --watch

或通过 package.json 配置快捷命令:

复制代码
{
  "scripts": {
    "dev": "tsc --watch",
    "build": "tsc"
  }
}
3.2 结合 ESLint 和 Prettier
  1. 安装依赖

    复制代码
    npm install eslint prettier eslint-config-prettier eslint-plugin-prettier @typescript-eslint/eslint-plugin @typescript-eslint/parser --save-dev
  2. 配置 .eslintrc.json

    复制代码
    {
      "root": true,
      "parser": "@typescript-eslint/parser",
      "plugins": ["@typescript-eslint"],
      "extends": [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended",
        "plugin:prettier/recommended"
      ],
      "rules": {
        "@typescript-eslint/no-unused-vars": "warn"
      }
    }
  3. 配置 .prettierrc

    复制代码
    {
      "semi": true,
      "singleQuote": true,
      "trailingComma": "all"
    }

4. 调试 TypeScript

4.1 配置调试器
  1. 在 VSCode 中按 F5 创建 launch.json,选择 Node.js 环境。

  2. 修改配置以支持 TypeScript:

    复制代码
    {
      "version": "0.2.0",
      "configurations": [
        {
          "type": "node",
          "request": "launch",
          "name": "Debug TS",
          "preLaunchTask": "tsc: build", // 触发编译任务
          "program": "${workspaceFolder}/src/index.ts",
          "outFiles": ["${workspaceFolder}/dist/**/*.js"],
          "sourceMaps": true // 启用 SourceMap
        }
      ]
    }

5. 打包与构建

5.1 使用 tsc 直接编译
复制代码
npm run build
5.2 使用打包工具
5.2.1 Webpack
  1. 安装依赖

    复制代码
    npm install webpack webpack-cli ts-loader --save-dev
  2. 配置 webpack.config.js

    复制代码
    const path = require('path');
    
    module.exports = {
      entry: './src/index.ts',
      mode: 'production',
      module: {
        rules: [
          {
            test: /\.ts$/,
            use: 'ts-loader',
            exclude: /node_modules/
          }
        ]
      },
      resolve: {
        extensions: ['.ts', '.js']
      },
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
      }
    };
  3. 运行打包

    复制代码
    npx webpack
5.2.2 Rollup
  1. 安装依赖

    复制代码
    npm install rollup rollup-plugin-typescript2 @rollup/plugin-node-resolve --save-dev
  2. 配置 rollup.config.js

    复制代码
    import typescript from 'rollup-plugin-typescript2';
    import { nodeResolve } from '@rollup/plugin-node-resolve';
    
    export default {
      input: 'src/index.ts',
      output: {
        file: 'dist/bundle.js',
        format: 'cjs'
      },
      plugins: [nodeResolve(), typescript()]
    };
  3. 运行打包

    复制代码
    npx rollup -c
5.3 使用现代工具(esbuild/swc)
  • esbuild(极速打包):

    复制代码
    npm install esbuild --save-dev
    复制代码
    npx esbuild src/index.ts --bundle --outfile=dist/bundle.js --platform=node

6. 高级优化

6.1 路径别名

tsconfig.json 中配置路径别名:

复制代码
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

同时需在打包工具(如 Webpack/Rollup)中配置对应的别名解析。

6.2 生成声明文件

tsconfig.json 中启用声明文件生成:

复制代码
{
  "compilerOptions": {
    "declaration": true,
    "declarationDir": "types"
  }
}

7. 项目结构建议

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

8. 推荐工作流

  1. 使用 tsc --watchts-node-dev 实时编译和运行。

  2. 通过 ESLint 和 Prettier 保持代码规范。

  3. 使用 Webpack/Rollup 进行生产打包。

  4. 结合 npm scripts 管理常用命令:

    复制代码
    {
      "scripts": {
        "dev": "tsc --watch",
        "build": "tsc",
        "lint": "eslint src --ext .ts",
        "bundle": "webpack --mode production"
      }
    }

通过以上配置和工具链,可以在 VSCode 中高效开发、调试和打包 TypeScript 项目。

相关推荐
..过云雨17 分钟前
04.【Linux系统编程】基础开发工具2(makefile、进度条程序实现、版本控制器Git、调试器gdb/cgdb的使用)
linux·笔记·学习
zzzsde28 分钟前
【Linux】初识Linux
linux·运维·服务器
fouryears_2341733 分钟前
云服务器使用代理稳定与github通信方法
运维·服务器·github
渡我白衣36 分钟前
Linux网络:应用层协议http
linux·网络·http
pofenx1 小时前
使用nps创建隧道,进行内网穿透
linux·网络·内网穿透·nps
Ronin3051 小时前
【Linux系统】单例式线程池
linux·服务器·单例模式·线程池·线程安全·死锁
desssq1 小时前
ubuntu 18.04 泰山派编译报错
linux·运维·ubuntu
Lzc7741 小时前
Linux的多线程
linux·linux的多线程
清风笑烟语1 小时前
Ubuntu 24.04 搭建k8s 1.33.4
linux·ubuntu·kubernetes
Dovis(誓平步青云)2 小时前
《Linux 基础指令实战:新手入门的命令行操作核心教程(第一篇)》
linux·运维·服务器