2026-10-09 06:35:48 +00:00
2026-10-09 06:35:48 +00:00
2022-03-14 21:17:36 +01:00
2022-03-14 21:17:36 +01:00
2023-08-26 14:52:12 +02:00
2026-10-09 06:35:48 +00:00

@git.zone/tswatch

A powerful, config-driven TypeScript file watcher that automatically recompiles and executes your project when files change. Built for modern TypeScript development with zero-config presets, smart bundling, a built-in dev server with live reload, and deep customization options.

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

✨ Features

  • 🔄 Config-driven architecture — Define watchers, bundles, and dev server in .smartconfig.json
  • ⚡ Zero-config presets — Get started instantly with npm, element, service, website, and test presets
  • 🧙 Interactive wizard — Run tswatch init to generate configuration interactively
  • 🌐 Built-in dev server — Live reload, CORS, compression, SPA fallback out of the box
  • 📦 Smart bundling — TypeScript, HTML, and assets with esbuild/rolldown/rspack integration
  • 🔁 Debounced execution — Configurable debounce prevents command spam during rapid file saves
  • 🛑 Process management — Automatic restart or queue mode for long-running commands
  • 🎯 Glob patterns — Watch any files with flexible pattern matching
  • 🧹 Graceful shutdown — Commands get SIGTERM and a grace period before their process tree is killed
  • 🏷️ Environment marker — Commands run by tswatch get TSWATCH=true, so libraries can enable development-only defaults

📦 Installation

# Global installation (recommended for CLI usage)
pnpm install -g @git.zone/tswatch

# As a dev dependency
pnpm install --save-dev @git.zone/tswatch

🚀 Quick Start

Using the Wizard

# Run the interactive wizard to create your configuration
tswatch init

The wizard guides you through creating a .smartconfig.json configuration with your chosen preset or custom watchers.

Using Presets

If you already have a configuration, just run:

tswatch

This reads your config from .smartconfig.json under the @git.zone/tswatch key and starts watching.

⚙️ Configuration

tswatch uses .smartconfig.json for configuration. Add your config under the @git.zone/tswatch key:

{
  "@git.zone/tswatch": {
    "preset": "npm"
  }
}

Available Presets

Preset Description
npm Watch ts/ and test/, run npm test on changes
test Watch ts/ and test/, run npm run test2 on changes
service Watch ts/, restart npm run startTs (ideal for backend services)
element Dev server on port 3002 + bundling for web components
website Full-stack: backend restart + frontend bundling + asset processing

Full Configuration Schema

{
  "@git.zone/tswatch": {
    "preset": "element",

    "server": {
      "enabled": true,
      "port": 3002,
      "serveDir": "./dist_watch/",
      "liveReload": true,
      "domain": "localhost"
    },

    "bundles": [
      {
        "name": "main-bundle",
        "from": "./ts_web/index.ts",
        "to": "./dist_watch/bundle.js",
        "watchPatterns": ["./ts_web/**/*"],
        "bundler": "esbuild",
        "production": false
      },
      {
        "name": "html",
        "from": "./html/index.html",
        "to": "./dist_watch/index.html",
        "watchPatterns": ["./html/**/*"]
      }
    ],

    "watchers": [
      {
        "name": "backend-build",
        "watch": "./ts/**/*",
        "command": "npm run build",
        "restart": false,
        "debounce": 300,
        "runOnStart": true
      },
      {
        "name": "tests",
        "watch": ["./ts/**/*", "./test/**/*"],
        "command": "npm test",
        "restart": true,
        "debounce": 300,
        "runOnStart": true
      }
    ]
  }
}

Configuration Options

ITswatchConfig

Option Type Description
preset string Use a preset: npm, test, service, element, website
watchers IWatcherConfig[] Array of watcher configurations
server IServerConfig Development server configuration
bundles IBundleConfig[] Bundle configurations

Tip: When a preset is specified alongside explicit watchers, bundles, or server, your explicit values take precedence over the preset defaults.

IWatcherConfig

Option Type Default Description
name string required Name for logging purposes
watch string | string[] required Glob pattern(s) to watch
command string — Shell command to execute on changes
restart boolean true Kill previous process before restarting
debounce number 300 Debounce delay in milliseconds
runOnStart boolean true Run the command immediately on start
stopGracePeriod number 10000 Milliseconds the command gets to exit after SIGTERM before its process tree is killed with SIGKILL

A command is stopped on restart, when its watcher stops and when tswatch shuts down (Ctrl+C or SIGTERM). tswatch sends SIGTERM to the command's process tree, waits up to stopGracePeriod for it to exit, then kills whatever remains with SIGKILL. A command that owns external resources (containers, ports, temporary state) gets the grace period to release them; a restart starts the new run only after the previous one ended.

IServerConfig

Option Type Default Description
enabled boolean required Whether the server is enabled
port number 3002 Server port; 0 picks a free port, which tswatch logs (Dev server started on port …)
serveDir string ./dist_watch/ Directory to serve
liveReload boolean true Inject the live reload client, which reloads the pages after every change of the served files
domain string localhost Domain name for the dev server

IBundleConfig

Option Type Default Description
name string — Name for logging purposes
from string required Entry point file
to string required Output file
watchPatterns string[] — Additional patterns to watch
outputMode 'bundle' | 'base64ts' 'bundle' Output mode for the bundle
bundler 'esbuild' | 'rolldown' | 'rspack' 'esbuild' Bundler engine to use
production boolean false Enable minification for production builds. A production bundle also gets tsbundle's third-party notices beside it, and the build fails when a bundled npm package ships no license text; supply that text or turn notices off under "@git.zone/tsbundle".thirdPartyNotices in the project's .smartconfig.json (see the @git.zone/tsbundle readme)
includeFiles (string | { from, to })[] — Additional files to include alongside the bundle
maxLineLength number — Max chars per line for base64ts output mode
codeSplitting boolean false Split the bundle at its dynamic import()s into chunk files below chunks/ beside it, as tsbundle's option of the same name does, so a watch build matches a production build that splits. Whatever serves the bundle serves chunks/ too; the dev server does for a bundle inside its serveDir

🛠️ CLI Commands

tswatch

Runs with configuration from .smartconfig.json. If no config exists, launches the interactive wizard automatically.

tswatch

--port <n> sets the dev server's port for this run, overriding server.port: a whole number from 1 to 65535, or 0 for a free port, which tswatch logs. It needs a configuration with an enabled dev server (server.enabled) and fails otherwise.

tswatch --port 4000

Ctrl+C or SIGTERM stops the dev server and the watchers; every command gets its stopGracePeriod first.

tswatch init

Force-run the configuration wizard (creates or overwrites existing config).

tswatch init

💻 Programmatic API

Basic Usage with Inline Config

import { TsWatch } from '@git.zone/tswatch';

const watcher = new TsWatch({
  watchers: [
    {
      name: 'my-watcher',
      watch: './src/**/*',
      command: 'npm run build',
      restart: true,
      debounce: 300,
      runOnStart: true,
    },
  ],
});

await watcher.start();

// Later: stop watching
await watcher.stop();

Load from Config File

import { TsWatch } from '@git.zone/tswatch';

// Load configuration from .smartconfig.json
const watcher = TsWatch.fromConfig();

if (watcher) {
  await watcher.start();
}

fromConfig() reads the .smartconfig.json of the process's working directory; TsWatch.fromConfig('/path/to/project') reads another project's.

Embedding TsWatch in an Application

TsWatch is a library as well as a CLI: an application can run it for a project and handle the process itself.

  • Project directory: new TsWatch(config, { cwd }) resolves the watch patterns, the bundles and the served directory against cwd and runs the commands in it; the default is process.cwd() when the TsWatch is constructed. ConfigHandler and TsWatch.fromConfig() take the directory as well.
  • Process lifecycle: TsWatch installs no process-global handlers. The application's entry point owns SIGINT, SIGTERM and the exit handling: it installs @push.rocks/smartexit's ProcessLifecycle once, with the shutdown deadline TsWatch needs, getShutdownTimeoutMs() (the longest stopGracePeriod of the watcher commands plus a margin), and stops TsWatch on shutdown. The tswatch CLI does exactly this. While a command runs, its process tree is registered with smartexit, so the application's shutdown and smartexit's exit safety net stop it.
  • Start and stop: stop() stops the dev server and the watchers and releases everything start() registered; repeated and concurrent calls share one stop, a stop during start() waits for the start, and the TsWatch starts again afterwards. serverPort is the port the dev server listens on (the picked one for port: 0).
  • Bundle events: onBundleEvent(listener) reports every bundle run: started, then finished with durationMs, or failed with durationMs and errorMessage. TsWatch keeps watching after a failed run. It returns the function that unsubscribes.
import { ProcessLifecycle, SmartExit } from '@push.rocks/smartexit';
import { ConfigHandler, TsWatch } from '@git.zone/tswatch';

const projectDir = '/path/to/project';
const config = new ConfigHandler(projectDir).loadConfig() ?? { bundles: [] };
const tsWatch = new TsWatch(config, { cwd: projectDir });

// The application's entry point owns the process lifecycle
ProcessLifecycle.install({ shutdownTimeoutMs: tsWatch.getShutdownTimeoutMs() });
new SmartExit({ silent: true }).addCleanupFunction(() => tsWatch.stop());

const unsubscribe = tsWatch.onBundleEvent((event) => {
  if (event.type === 'failed') {
    console.error(`${event.name} failed after ${event.durationMs} ms: ${event.errorMessage}`);
  }
});

await tsWatch.start();
console.log(`serving on port ${tsWatch.serverPort}`);

// Later
unsubscribe();
await tsWatch.stop();

Using ConfigHandler

import { ConfigHandler } from '@git.zone/tswatch';

// Reads .smartconfig.json of the process's working directory; new ConfigHandler(dir) reads dir's
const configHandler = new ConfigHandler();

// Check if config exists
if (configHandler.hasConfig()) {
  const config = configHandler.loadConfig();
  console.log(config);
}

// Get available presets
const presets = configHandler.getPresetNames();
// => ['npm', 'test', 'service', 'element', 'website']

// Get a specific preset
const npmPreset = configHandler.getPreset('npm');

Using Watcher Directly

For more granular control, use the Watcher class:

import { Watcher } from '@git.zone/tswatch';

// Create from config object
const watcher = Watcher.fromConfig({
  name: 'my-watcher',
  watch: ['./src/**/*', './lib/**/*'],
  command: 'npm run compile',
  restart: true,
});

await watcher.start();

Using Function Callbacks

import { Watcher } from '@git.zone/tswatch';

const watcher = new Watcher({
  name: 'custom-handler',
  filePathToWatch: './src/**/*',
  functionToCall: async () => {
    console.log('Files changed! Running custom logic...');
    // Your custom build/test/deploy logic here
  },
  debounce: 500,
  runOnStart: true,
});

await watcher.start();

📁 Project Structure Examples

NPM Package / Node.js Library

project/
├── ts/                 # TypeScript source files
├── test/               # Test files
├── package.json        # With "test" script
└── .smartconfig.json   # tswatch config
{
  "@git.zone/tswatch": {
    "preset": "npm"
  }
}

Backend Service

project/
├── ts/                 # TypeScript source files
├── package.json        # With "startTs" script
└── .smartconfig.json
{
  "@git.zone/tswatch": {
    "preset": "service"
  }
}

Web Component / Element

project/
├── ts/                 # Backend TypeScript (optional)
├── ts_web/             # Frontend TypeScript
├── html/
│   ├── index.ts        # Web entry point
│   └── index.html
├── dist_watch/         # Output (auto-created)
└── .smartconfig.json
{
  "@git.zone/tswatch": {
    "preset": "element"
  }
}

Access your project at http://localhost:3002

Full-Stack Website

project/
├── ts/                 # Backend TypeScript
├── ts_web/             # Frontend TypeScript
│   └── index.ts
├── html/
│   └── index.html
├── assets/             # Static assets
├── dist_serve/         # Output
└── .smartconfig.json
{
  "@git.zone/tswatch": {
    "preset": "website"
  }
}

🌐 Development Server

The built-in development server (powered by @api.global/typedserver's UtilityWebsiteServer) is enabled in the element preset and in any configuration with server.enabled:

  • 👀 File Watching — The server watches serveDir, so its app version follows the served files, whether a bundle or a watcher command wrote them
  • 🔄 Live Reload — After every change of the served files, the injected live reload client reloads the pages over a WebSocket
  • 🚫 No Stale Files — Served files are Cache-Control: no-cache and revalidated against their ETag on every request; routes and built-in endpoints are no-store
  • 🌍 CORS — Cross-origin requests enabled
  • 🗜️ Compression — Brotli + gzip compression for faster loading
  • 📱 SPA Fallback — Single-page application routing support
  • 🔒 Security Headers — Cross-origin isolation (COOP, COEP)
  • 📦 PWA Manifest — Auto-generated Progressive Web App manifest
  • ⚡ Service Worker — typedserver's service worker, which drops its caches after every change of the served files

Default configuration:

Setting Default
Port 3002
Serve Directory ./dist_watch/
Live Reload Enabled
Domain localhost

With liveReload: false the pages carry no live reload client. The served files are still watched, so a page that uses typedserver's service worker client handles each change as a new app version, as its autoReload setting says: it reloads, or with autoReload: false it reports update-available.

The dev server serves the service worker of @api.global/typedserver 13. A page that bundles the service worker client of typedserver 12 or earlier does not hear of new versions from it; update the app to typedserver 13 or later.

🏷️ Environment Marker

Every command a watcher runs gets TSWATCH=true in its environment, and so does everything that command starts: the commands of your watchers, the test runs of the npm and test presets and the apps the service and website presets start. tswatch leaves its own process environment unchanged; its dev server gets its options from tswatch directly.

@api.global/typedserver 13 and later turns on the development defaults of UtilityWebsiteServer, live reload and file watching, from it. An app that a watcher command starts keeps those defaults without any change, while the same app started in production does not get them. A test suite that a watcher runs gets them as well; a test that needs the production behavior passes injectReload and watch explicitly.

The name and value are exported as TSWATCH_ENV_VAR_NAME and TSWATCH_ENV_VAR_VALUE:

import { TSWATCH_ENV_VAR_NAME, TSWATCH_ENV_VAR_VALUE } from '@git.zone/tswatch';

const runByTswatch = process.env[TSWATCH_ENV_VAR_NAME] === TSWATCH_ENV_VAR_VALUE;

A library that does not depend on tswatch checks process.env.TSWATCH === 'true'.

🔧 Configuration Tips

  1. Use presets for common workflows — They're battle-tested and cover most use cases
  2. Customize with explicit config — Override preset defaults by adding explicit watchers, bundles, or server config
  3. Debounce wisely — Default 300ms works well; increase for slower builds
  4. Use restart: false for one-shot commands (like builds) and restart: true for long-running processes (like servers)
  5. Multiple bundlers — Choose between esbuild (fastest), rolldown (smallest output), or rspack (webpack-compatible) per bundle

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the license.md file.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

S
Description
watch typescript projects during development
Readme
3.9 MiB
Languages
TypeScript 99.6%
JavaScript 0.4%