16. 编译与构建工具
16. 编译与构建工具
1. 概述
TypeScript 编译和构建工具是将 TypeScript 代码转换为 JavaScript 的关键环节。选择合适的构建工具可以显著提升开发效率和构建性能。
┌─────────────────────────────────────────────────────────────┐ │ TypeScript 构建工具生态 │ ├─────────────────────────────────────────────────────────────┤ │ │ │ 官方工具 │ │ ├── tsc:TypeScript 官方编译器 │ │ ├── tsserver:语言服务 │ │ └──TSPlayground:在线体验 │ │ │ │ 打包工具集成 │ │ ├── Webpack:ts-loader、awesome-typescript-loader │ │ ├── Vite:@vitejs/plugin-react-swc、vite-plugin-checker │ │ ├── Rollup:@rollup/plugin-typescript │ │ ├── esbuild:原生支持 TypeScript │ │ └──SWC:@swc/core,极速编译 │ │ │ │ 其他工具 │ │ ├── ts-node:直接运行 TypeScript │ │ ├── tsx:快速运行 TypeScript(基于 esbuild) │ │ ├── ts-jest:Jest 的 TypeScript 支持 │ │ └── tsd:类型定义测试 │ │ │ └─────────────────────────────────────────────────────────────┘2. tsc 命令行工具
2.1 基本命令
# 编译 TypeScript 文件tsc index.ts# 监听模式tsc--watchtsc-w# 指定配置文件tsc-ptsconfig.json tsc--projecttsconfig.json# 生成配置文件tsc--init# 输出版本信息tsc--version# 显示配置tsc--showConfig2.2 常用参数
# 指定输出目录tsc--outDir./dist# 指定输出文件tsc--outFile./bundle.js# 生成声明文件tsc--declaration# 生成 source maptsc--sourceMap# 移除注释tsc--removeComments# 严格模式tsc--strict# 跳过库检查tsc--skipLibCheck# 增量编译tsc--incremental2.3 项目引用构建
# 构建项目引用tsc--buildtsc-b# 清理构建tsc--build--clean# 强制重建tsc--build--force# 详细输出tsc--build--verbose3. Webpack 集成
3.1 使用 ts-loader
npminstall--save-dev typescript ts-loader webpack webpack-cli// webpack.config.jsconstpath=require('path');module.exports={mode:'development',entry:'./src/index.ts',output:{path:path.resolve(__dirname,'dist'),filename:'bundle.js'},resolve:{extensions:['.ts','.js']},module:{rules:[{test:/\.ts$/,use:'ts-loader',exclude:/node_modules/}]},devtool:'source-map'};3.2 使用 awesome-typescript-loader
npminstall--save-dev awesome-typescript-loader// webpack.config.jsmodule.exports={module:{rules:[{test:/\.ts$/,use:'awesome-typescript-loader',exclude:/node_modules/}]}};3.3 Fork TS Checker
npminstall--save-dev fork-ts-checker-webpack-plugin// webpack.config.jsconstForkTsCheckerWebpackPlugin=require('fork-ts-checker-webpack-plugin');module.exports={plugins:[newForkTsCheckerWebpackPlugin({typescript:{configFile:'./tsconfig.json'}})]};4. Vite 集成
4.1 创建 Vite + TypeScript 项目
# 创建项目npmcreate vite@latest my-app ----templatereact-ts# 或 Vue + TypeScriptnpmcreate vite@latest my-app ----templatevue-ts# 安装依赖cdmy-appnpminstall4.2 Vite 配置
// vite.config.tsimport{defineConfig}from'vite';importreactfrom'@vitejs/plugin-react';// 使用 SWC 加速编译importreactfrom'@vitejs/plugin-react-swc';exportdefaultdefineConfig({plugins:[react()],resolve:{alias:{'@':'/src','@components':'/src/components'}},build:{outDir:'dist',sourcemap:true}});4.3 类型检查插件
npminstall--save-dev vite-plugin-checker// vite.config.tsimportcheckerfrom'vite-plugin-checker';exportdefaultdefineConfig({plugins:[checker({typescript:true,eslint:{lintCommand:'eslint "./src/**/*.{ts,tsx}"'}})]});5. Rollup 集成
5.1 使用 @rollup/plugin-typescript
npminstall--save-dev rollup @rollup/plugin-typescript typescript tslib// rollup.config.jsimporttypescriptfrom'@rollup/plugin-typescript';exportdefault{input:'src/index.ts',output:{dir:'dist',format:'esm',sourcemap:true},plugins:[typescript({tsconfig:'./tsconfig.json',declaration:true,declarationDir:'./dist/types'})]};5.2 库打包配置
// rollup.config.jsimporttypescriptfrom'@rollup/plugin-typescript';importresolvefrom'@rollup/plugin-node-resolve';importcommonjsfrom'@rollup/plugin-commonjs';exportdefault[// ESM 构建{input:'src/index.ts',output:{file:'dist/index.esm.js',format:'esm',sourcemap:true},plugins:[typescript()],external:['react','react-dom']},// CJS 构建{input:'src/index.ts',output:{file:'dist/index.cjs.js',format:'cjs',sourcemap:true},plugins:[typescript()],external:['react','react-dom']}];6. esbuild 集成
6.1 直接使用 esbuild
npminstall--save-dev esbuild// build.jsconstesbuild=require('esbuild');asyncfunctionbuild(){awaitesbuild.build({entryPoints:['src/index.ts'],bundle:true,outfile:'dist/bundle.js',platform:'node',target:'node16',sourcemap:true,minify:true});}build();6.2 命令行使用
# 基本编译esbuild src/index.ts--outfile=dist/index.js# 打包esbuild src/index.ts--bundle--outfile=dist/bundle.js# 压缩esbuild src/index.ts--minify--outfile=dist/index.js# 监听模式esbuild src/index.ts--watch--outfile=dist/index.js# 生成 source mapesbuild src/index.ts--sourcemap--outfile=dist/index.js7. SWC(Speedy Web Compiler)
7.1 安装和配置
npminstall--save-dev @swc/cli @swc/core// .swcrc{"jsc":{"parser":{"syntax":"typescript","tsx":true,"decorators":true},"target":"es2020","transform":{"react":{"runtime":"automatic"}}},"module":{"type":"es6"},"sourceMaps":true,"minify":false}7.2 使用 SWC 编译
# 编译单个文件npx swc src/index.ts-odist/index.js# 编译整个目录npx swc src-ddist# 监听模式npx swc src-ddist-w8. ts-node 和 tsx
8.1 ts-node
# 安装npminstall--save-dev ts-node# 运行 TypeScript 文件npx ts-node src/index.ts# 监听模式npx ts-node--watchsrc/index.ts# 跳过类型检查npx ts-node --transpile-only src/index.ts// ts-node 配置{"ts-node":{"compilerOptions":{"module":"commonjs"},"transpileOnly":true,"files":true}}8.2 tsx
# 安装npminstall--save-dev tsx# 运行 TypeScript 文件npx tsx src/index.ts# 监听模式npx tsx--watchsrc/index.ts# 生产模式npx tsx--conditions=production src/index.ts9. Jest 集成
9.1 ts-jest 配置
npminstall--save-dev jest @types/jest ts-jest// jest.config.jsmodule.exports={preset:'ts-jest',testEnvironment:'node',roots:['<rootDir>/src'],testMatch:['**/*.test.ts'],collectCoverageFrom:['src/**/*.ts'],coverageDirectory:'coverage'};9.2 使用 SWC 加速
npminstall--save-dev @swc/jest// jest.config.jsmodule.exports={transform:{'^.+\\.tsx?$':['@swc/jest']},testEnvironment:'node'};10. 性能对比
| 工具 | 编译速度 | 特性支持 | 生态集成 | 适用场景 |
|---|---|---|---|---|
| tsc | ⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | 类型检查、声明生成 |
| Webpack + ts-loader | ⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | 复杂应用打包 |
| Vite | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | 现代前端开发 |
| esbuild | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | 快速构建、工具链 |
| SWC | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | Rust 生态、极速编译 |
| ts-node | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | 开发调试 |
| tsx | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | 快速运行脚本 |
11. 完整示例:多环境构建配置
// scripts/build.jsconstesbuild=require('esbuild');constfs=require('fs');constpath=require('path');constisDev=process.env.NODE_ENV==='development';constisProd=process.env.NODE_ENV==='production';asyncfunctionbuild(){constconfig={entryPoints:['src/index.ts'],bundle:true,sourcemap:isDev,minify:isProd,target:'es2020',platform:'node',outfile:'dist/index.js',external:['express','react','react-dom'],define:{'process.env.NODE_ENV':JSON.stringify(process.env.NODE_ENV),'__DEV__':isDev,'__PROD__':isProd}};if(isDev){// 开发模式:监听文件变化constcontext=awaitesbuild.context(config);awaitcontext.watch();console.log('Watching for changes...');}else{// 生产模式:一次构建awaitesbuild.build(config);console.log('Build completed!');}}build().catch(console.error);// package.json{"scripts":{"dev":"NODE_ENV=development node scripts/build.js","build":"NODE_ENV=production node scripts/build.js","start":"node dist/index.js","type-check":"tsc --noEmit","test":"jest"}}12. 总结
| 场景 | 推荐工具 | 理由 |
|---|---|---|
| 类型检查 | tsc | 官方工具,最完整 |
| 声明生成 | tsc | 唯一支持 |
| 前端应用 | Vite | 开发体验好 |
| 库打包 | Rollup | 输出干净 |
| 快速构建 | esbuild/SWC | 速度快 |
| Node.js 开发 | tsx | 简单快速 |
| 复杂应用 | Webpack | 生态丰富 |
13. 第三部分总结
恭喜你完成了第三部分:模块与工程化!
你已掌握:
- ✅ 模块系统(导入/导出、动态导入)
- ✅ 声明文件(编写、发布、扩展)
- ✅ tsconfig 配置(编译选项、严格模式、项目引用)
- ✅ 编译与构建工具(tsc、Webpack、Vite、Rollup、esbuild、SWC)
