如何将tsc --watch类型检查与自带监听的esbuild构建脚本结合?
结合tsc --watch与esbuild构建脚本的实用方法
有几种简单可行的方式可以把tsc的类型检查监听和你的esbuild构建脚本结合起来,根据你的需求选择即可:
1. 并行启动两个监听进程(最常用、零侵入)
这种方式让tsc和esbuild各自独立运行监听,互不干扰,实现成本最低:
- 先安装
concurrently工具(用来并行执行多个命令):npm install concurrently --save-dev - 在项目的
package.json里添加以下脚本:"scripts": { "type-check:watch": "tsc --noEmit --incremental --watch", "build:watch": "node ./build-with-esbuild.js", "dev": "concurrently \"npm run type-check:watch\" \"npm run build:watch\"" } - 执行
npm run dev就能同时启动tsc的类型检查监听和esbuild的构建监听,tsc会在控制台输出类型错误,esbuild正常处理文件变化的构建。
2. 在esbuild脚本中集成tsc监听(类型检查通过才构建)
如果希望只有类型检查通过时才触发esbuild构建,可以直接修改你的build-with-esbuild.js脚本,用TypeScript的API启动监听并绑定回调:
const { watch: tscWatch } = require('typescript'); const { build: esbuildBuild } = require('esbuild'); const tsConfig = require('./tsconfig.json'); // 启动tsc增量类型检查监听 const tscWatcher = tscWatch(tsConfig, { noEmit: true, incremental: true }); // 当tsc类型检查完成时触发逻辑 tscWatcher.on('finished', (diagnostics) => { // 筛选出类型错误 const hasTypeErrors = diagnostics.some(d => d.category === 1); if (!hasTypeErrors) { console.log('类型检查通过,开始构建...'); // 启动esbuild构建并保持监听 esbuildBuild({ // 这里填你的esbuild原有配置 entryPoints: ['src/index.ts'], outfile: 'dist/bundle.js', watch: true, // 其他配置... }).catch(err => { console.error('esbuild构建失败:', err); process.exit(1); }); } else { console.error('存在类型错误,跳过本次构建'); // 可以在这里打印具体错误信息 diagnostics.forEach(d => { if (d.category === 1) { console.error(`[类型错误] ${d.messageText}`); } }); } }); tscWatcher.on('failed', () => { console.error('tsc监听服务启动失败'); process.exit(1); });
这种方式能确保只有类型正确的代码才会被构建,但需要你调整原有esbuild脚本的结构。
3. 用Shell脚本并行启动(无额外依赖)
如果不想安装额外工具,可以用Shell脚本直接并行启动两个进程:
- 在项目根目录创建
dev.sh文件:#!/bin/bash # 启动tsc监听,后台运行 tsc --noEmit --incremental --watch & # 启动esbuild构建脚本 node ./build-with-esbuild.js & # 等待所有后台进程结束 wait - 给脚本添加执行权限:
chmod +x dev.sh - 运行脚本:
./dev.sh
注:Windows用户可以用批处理文件(
.bat)或者WSL来执行类似逻辑。
内容的提问来源于stack exchange,提问作者Yudi Supriyadi
相关产品推荐
相关产品推荐

