在 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 项目。

相关推荐
RisunJan8 分钟前
Linux命令-gpasswd命令(管理用户组的重要工具)
linux·运维·服务器
where happens23 分钟前
centos创建目录并授予权限
linux·运维·服务器·centos
liebe1*139 分钟前
第七章 防火墙地址转换
运维·服务器·网络
好好学操作系统1 小时前
autodl 保存 数据 跨区
linux·运维·服务器
dbitc1 小时前
WIN11把WSL2移动安装目录
linux·运维·ubuntu·wsl
KingRumn1 小时前
Linux同步机制之信号量
linux·服务器·网络
嵌入式学习菌1 小时前
SPIFFS文件系统
服务器·物联网
旺仔Sec1 小时前
2026年度河北省职业院校技能竞赛“Web技术”(高职组)赛项竞赛任务
运维·服务器·前端
BullSmall1 小时前
linux 根据端口查看进程
linux·运维·服务器
herinspace1 小时前
管家婆软件年结存后快马商城操作注意事项
服务器·数据库·windows