@git.zone/tsbundle
A powerful multi-bundler tool supporting esbuild, rolldown, and rspack for painless bundling of web projects.
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.
Installation
# Global installation for CLI usage
pnpm add -g @git.zone/tsbundle
# Local installation for project usage
pnpm add --save-dev @git.zone/tsbundle
Quick Start
Interactive Setup
The easiest way to get started is with the interactive wizard:
tsbundle init
This guides you through setting up your bundle configuration with preset options:
- element - Web component / element bundle (
./ts_web/index.ts->./dist_bundle/bundle.js) - website - Full website with HTML and assets (
./ts_web/index.ts->./dist_serve/bundle.js) - npm - NPM package bundle (
./ts/index.ts->./dist_bundle/bundle.js) - custom - Configure everything manually
Build Your Bundles
Once configured, simply run:
tsbundle
Your bundles will be built according to your .smartconfig.json configuration.
CLI Commands
| Command | Description |
|---|---|
tsbundle |
Build all bundles from .smartconfig.json configuration |
tsbundle --keep-temp |
Build all bundles and keep their .nogit/tsbundle-temp-* workspaces for debugging |
tsbundle custom |
Same as above (explicit) |
tsbundle init |
Interactive wizard to create/update bundle configuration |
tsbundle element |
Zero-config compatibility preset for ts_web component bundles |
tsbundle website |
Zero-config compatibility preset for website bundles, HTML, and assets |
tsbundle npm |
Zero-config compatibility preset for ts/index.ts bundles |
The preset commands remain available for established package scripts and accept flags such as --production, --bundler, --sourcemap, and --keep-temp. New projects should prefer explicit .smartconfig.json configuration.
Configuration
tsbundle uses .smartconfig.json for configuration. Here's an example:
{
"@git.zone/tsbundle": {
"keepTemp": false,
"bundles": [
{
"from": "./ts_web/index.ts",
"to": "./dist_bundle/bundle.js",
"outputMode": "bundle",
"bundler": "esbuild",
"production": false,
"sourcemap": false
},
{
"from": "./ts_web/index.ts",
"to": "./dist_serve/bundle.js",
"outputMode": "bundle",
"bundler": "esbuild",
"includeFiles": ["./html/**/*.html", "./assets/**/*"]
}
]
}
}
Bundle Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
from |
string |
- | Entry point TypeScript file |
to |
string |
- | Output file path |
outputMode |
"bundle" | "base64ts" |
"bundle" |
Output format (see below) |
bundler |
"esbuild" | "rolldown" | "rspack" |
"esbuild" |
Which bundler to use |
production |
boolean |
false |
Enable minification |
sourcemap |
boolean |
true |
Control external source-map generation |
banner |
string |
- | Valid JavaScript inserted verbatim before every JavaScript output, including emitted workers |
tsconfigPath |
string |
nearest tsconfig.json |
The tsconfig.json whose compilerOptions the bundle is compiled with (see below) |
includeFiles |
(string | { from: string; to: string })[] |
[] |
Files published with the bundle, placed by the same rule in both output modes (see Included Files) |
maxLineLength |
number |
0 (unlimited) |
For base64ts mode: max chars per line in output |
keepTemp |
boolean |
false |
Keep the bundle's .nogit/tsbundle-temp-* workspace for debugging |
thirdPartyNotices |
boolean |
value of production |
Emit third-party notices beside the bundle (see Third-Party Notices); overrides the top-level thirdPartyNotices.enabled |
Top-level keepTemp: true keeps the temp workspace for all bundles. Per-bundle keepTemp only affects that bundle. TSBUNDLE_KEEP_TEMP=true and --keep-temp are supported for one-off debugging.
Use banner for content that must remain attached to every generated JavaScript artifact,
such as a license or attribution comment. The value is inserted verbatim and therefore
must be valid JavaScript; a block comment is the usual form. Esbuild, Rolldown, and Rspack
apply the same option through their native banner support.
Included Files
includeFiles entries are published with the bundle: beside the bundle file in bundle mode, as embedded paths in base64ts mode. Both modes place every file by one rule, relative to that output root:
| Entry | Lands at |
|---|---|
"./html/index.html" |
index.html - a file keeps its name |
"./html/*" |
every file directly in html/, under its name |
"./html/**/*" or "./html/**" |
every file below html/, at its path below html/ - subdirectories are kept |
"./html/**/*.js" |
every .js file below html/, at any depth, at its path below html/ |
{ "from": "./html/index.html", "to": "app/start.html" } |
app/start.html |
{ "from": "./html/**/*", "to": "static" } |
static/<path below html/> |
Globs are matched by Node's fs.glob: * matches within one path segment (*.js does not match app.json), ** matches any number of directories, and ?, […], {a,b} and extglobs work as usual. Files and directories whose name starts with a dot are matched only by a segment that names the dot, such as "./html/.well-known/*". / and \ both separate path segments on every platform and in every part of the pattern, as they do for fs.glob, so "html\\*.js" places its files the same way on Linux, macOS and Windows. The glob root is the directory in front of the first path segment that holds a glob character; the path root itself (/, a drive or a UNC share) is always literal. A .. segment after the first glob segment would leave the glob root, so such a pattern fails the build with an error that names it.
to must be a relative path inside the output root; a trailing slash is ignored, so "static/" and "static" name the same path. An absolute to, one that climbs out with .., or one that names the output root itself (".", "./") fails the build with an error that names it. An included file that lands on another included file or on a generated artifact fails the build instead of producing ambiguous output. A missing file or glob root is logged and skipped.
Temporary Workspace Cleanup
Each custom bundle build uses a unique project-local .nogit/tsbundle-temp-* intermediate workspace. tsbundle writes .gitzone-tool-cache.json into the workspace and removes it after output handling unless keepTemp is enabled. The marker records the owning process so concurrent builds do not delete each other's active workspaces. On startup, marked workspaces older than 24 hours whose owner is no longer running are pruned so interrupted builds do not accumulate indefinitely.
Legacy .nogit/tsbundle-temp and OS temp workspaces with valid stale tsbundle markers are also pruned. An unmarked legacy workspace is never claimed or deleted.
Output Modes
bundle (default)
Standard JavaScript bundle output. Files named by includeFiles are published into the output directory as described in Included Files. Generated chunks, module workers, and enabled source maps are preserved beside the main bundle.
All direct backends and custom publication acquire both output-directory and destination locks so generated and included files cannot interleave. If generation or publication reports an error before the main-file commit, tsbundle restores mutable files and leaves the previous bundle intact. After a successful commit, it removes stale worker chunks and source maps that it owns without deleting neighboring bundle artifacts. Each owned namespace records that ownership in chunks/<namespace>/.tsbundle-artifacts.json.
base64ts
Generates a TypeScript file with base64-encoded content - perfect for Deno compile scenarios where you need everything embedded in a single executable:
// Auto-generated by tsbundle
export const files: { path: string; contentBase64: string }[] = [
{ path: "bundle.js", contentBase64: "Y29uc3QgaGVsbG8gPSAid29ybGQi..." },
{ path: "bundle.js.map", contentBase64: "eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbLi4u" },
{ path: "bundle.js.third-party-notices.json", contentBase64: "ewogICJnZW5lcmF0b3IiOi..." },
{ path: "bundle.js.third-party-notices.txt", contentBase64: "VGhpcmQtcGFydHkgbm90aWNl..." },
{ path: "index.html", contentBase64: "PCFET0NUWVBFIGh0bWw+..." },
];
If you're working with AI tools that have line length limitations, set maxLineLength (e.g., 200) to split long base64 strings across multiple lines.
Third-Party Notices
MIT, BSD, ISC and Apache licenses require their copyright and license text to travel with every copy of the code, and a minified bundle drops most of the comments that carry it. So every production bundle gets two files beside it that list each npm package whose code ended up in the bundle - its chunks and module workers included - with the full text of the license and notice files the package ships (LICENSE*, LICENCE*, COPYING*, NOTICE*, THIRD-PARTY-NOTICES*, in any case):
| File | Content |
|---|---|
<bundle>.third-party-notices.txt |
Human-readable: one section per name@version with its declared license and file texts |
<bundle>.third-party-notices.json |
{ generator, packages: [{ name, version, license, files: [{ name, origin, sha256, text }] }] } |
For dist_serve/bundle.js these are dist_serve/bundle.js.third-party-notices.txt and .json; base64ts output embeds both next to bundle.js. Ship them with the bundle, or merge them into the notices of the binary or image that embeds it. Packages are sorted by name and version, files by origin and name, and neither file holds a timestamp or an absolute path, so the same dependency tree yields byte-identical notices on every machine.
Every module the bundler placed in the output is attributed to the package directory below its last node_modules segment, so pnpm's .pnpm layout and nested installs resolve to the package that actually shipped the code. Modules outside node_modules - your own sources and workspace-local packages - and the package named by the package.json in the working directory are first-party and not listed. All three bundlers are covered: esbuild through its metafile, including every emitted module worker, rolldown through the modules of each output chunk, rspack through the modules its chunks hold, the ones a concatenated module inlined included.
Notices default to on for production: true bundles and off otherwise; a build without notices removes the pair an earlier build left at its destination. Set thirdPartyNotices on a bundle, or thirdPartyNotices.enabled for the whole project, to decide explicitly.
Packages without license text
Some packages declare a license in package.json but publish no license file. tsbundle does not guess their copyright notice: the build fails and names each such package@version, its declared license and its directory. The text comes from a supplement - shipped by the library that depends on the package (see Shipping supplements with a library), or reviewed and added in the project configuration:
{
"@git.zone/tsbundle": {
"thirdPartyNotices": {
"supplements": [
{
"packages": ["@tiptap/core", "@tiptap/pm", "@tiptap/starter-kit"],
"license": "MIT",
"licenseFile": "./licenses/tiptap.txt"
},
{
"packages": ["@xterm/addon-serialize@0.14.0"],
"license": "MIT",
"licenseFile": "./licenses/xterm.txt"
}
]
},
"bundles": [ ... ]
}
}
packageslistsnameorname@versionentries. A pinned entry covers that version only; a bare name covers every version whose declared license equalslicense, so a package that changes its license fails the build again instead of inheriting the old text. A package that declares no license at all must be pinned.licensemust equal the license the package declares; a mismatch fails the build.licenseFileis read relative to the project directory and appears in the notices with originsupplementandsuppliedBy: "project", under its project-relative path.- A supplement also applies to a package that ships its own files, adding the text next to them. Supplements that match no bundled package are ignored, so one list serves every bundle of the project.
- One configuration covering the same
package@versiontwice fails the build. When several providers - the project, the options of a programmatic build and bundled packages - cover the samepackage@version, they must supply the same license with byte-identical text; the notices then carry it once, preferring the project's entry, then the build options'. Different text fails the build with a conflict error that names every provider and entry. The project does not override a library: remove whichever entry is wrong. Identical text is accepted so that two bundled copies of one library, or a project that still carries text a dependency now ships, do not block the build.
The only way past a package without text is a supplement or turning notices off for that bundle with "thirdPartyNotices": false.
Shipping supplements with a library
A library that depends on a package without license text should ship that text itself, so every project that bundles the library inherits it instead of repeating the same supplements. tsbundle reads the .smartconfig.json in the root of every package whose code is in the bundle and applies its "@git.zone/tsbundle".thirdPartyNotices.supplements exactly like the project's own; the rest of that file - the library's bundles, enabled and other tools' settings - is ignored. The library's own builds - through the CLI or TsBundle.build() - read the same entries, so one declaration covers both.
-
Put the reviewed license texts in the library, for example under
licenses/, and list them in the library's.smartconfig.json:{ "@git.zone/tsbundle": { "thirdPartyNotices": { "supplements": [ { "packages": ["@tiptap/core", "@tiptap/pm", "@tiptap/starter-kit"], "license": "MIT", "licenseFile": "./licenses/tiptap.txt" } ] } } } -
Publish both: add
.smartconfig.jsonand the license directory to thefilesarray of the library'spackage.json, for example".smartconfig.json"and"licenses/**/*".
licenseFile resolves against the library's package root and must stay inside it; a path that leaves the package fails the build, and so does a symbolic link that leads outside it - the file's real path must lie inside the package's real root, which also holds when pnpm links the package in. The supplement applies only while the library's own code is in the bundle, and the notices show it as suppliedBy: "<library>@<version>". Prefer bare package names in a library: a pinned version breaks the supplement on every patch release of the dependency, while a bare name stays valid as long as the dependency keeps declaring the same license.
Esbuild keeps its default legalComments behavior (eof): comments marked /*!, @license or @preserve stay at the end of the bundle. They carry only what an author chose to mark, usually a copyright line without the license text, so the notices files are the complete record; tsbundle does not additionally switch esbuild to linked or external legal comments.
Programmatic TsBundle.build() calls resolve notices exactly like the CLI: they read "@git.zone/tsbundle".thirdPartyNotices from the .smartconfig.json in the cwd they are given, so the project's enabled and supplements apply without being repeated. The thirdPartyNotices: { enabled?, supplements? } option adds to that configuration:
enabledin the options wins over the project'sthirdPartyNotices.enabled, which wins over the default ofproduction. On the CLI path a bundle'sthirdPartyNoticesflag takes the place of the option.supplementsin the options do not replace the project's: both apply, as separate providers of equal standing under the rules above. TheirlicenseFilepaths are read relative to thecwd, and their text appears withsuppliedBy: "build options"; where the project and the options cover the samepackage@version, identical text is listed once as the project's and different text fails the build.
Module Workers With Esbuild
The esbuild backend recognizes standard module-worker construction and emits the worker as a separate collision-safe chunk:
const worker = new Worker(new URL('./worker.js', import.meta.url), {
type: 'module',
});
Both direct .ts worker references and NodeNext-style .js specifiers are supported; .js references resolve to the corresponding TypeScript source when present. Acyclic nested worker graphs are emitted recursively, and reused workers are built once while receiving the correct URL from every parent. Cyclic worker graphs reject the build. Direct and custom bundle output publishes worker chunks and source maps with the main bundle, while base64ts includes them in its generated file list. Rebuilding the same destination replaces its owned worker artifact set without affecting files owned by another bundle.
TypeScript Configuration
A bundle is compiled with the compilerOptions of your project, not with a configuration of
tsbundle's own. The governing tsconfig.json is chosen in this order, and the chosen file is
logged on every build:
- the
tsconfigPathoption, when set - a relative path is resolved against the working directory, and a path that does not exist fails the build, - the nearest
tsconfig.jsonin or above the directory of the entry point, - the
tsconfig.jsonof the working directory, for entry points outside the project, - tsbundle's packaged default
tsconfig.json, when the project has none.
The entry point decides, not the output path, so bundling into a cache or temp directory still
uses the configuration your sources are written against. extends chains are resolved.
Each bundler reads that file itself, so baseUrl and paths - wildcard mappings included - are
resolved by the bundler's own TypeScript support; tsbundle derives no aliases of its own. A
NodeNext-style .js specifier resolves to the TypeScript source it names under every bundler.
Esbuild acts on experimentalDecorators, useDefineForClassFields, target (only as the
default for useDefineForClassFields), baseUrl, paths, strict, alwaysStrict,
verbatimModuleSyntax, importsNotUsedAsValues, preserveValueImports and the jsx* options;
rolldown additionally acts on emitDecoratorMetadata and strictNullChecks. Rspack is given
experimentalDecorators, emitDecoratorMetadata and useDefineForClassFields explicitly, and
resolves baseUrl and paths from the same file. Everything else, including module and
moduleResolution, is decided by tsbundle: the output is always an ES module targeting ES2022.
When useDefineForClassFields is not set, define semantics apply only if the configuration
declares a target of ES2022 or higher. That is esbuild's rule, applied to all three bundlers so
a bundle keeps its meaning when the bundler is switched.
emitDecoratorMetadata cannot be honoured by esbuild, which does not type-check, so an esbuild
bundle whose configuration enables it fails with an explicit error instead of silently losing the
metadata. Rolldown and rspack emit the metadata, and the error names them as the way to keep the
option.
Available Bundlers
tsbundle supports three modern bundlers, each with different strengths:
| Bundler | Speed | Bundle Size | Best For |
|---|---|---|---|
| esbuild | Fastest | Medium | Development, quick iterations |
| rolldown | Fast | Smallest | Production builds, tree-shaking |
| rspack | Fast | Largest (webpack runtime) | Webpack compatibility |
API Usage
TsBundle Class
The core bundling class, usable programmatically:
import { TsBundle } from '@git.zone/tsbundle';
const bundler = new TsBundle();
await bundler.build(
process.cwd(), // Working directory
'./src/index.ts', // Entry point
'./dist/bundle.js', // Output path
{
bundler: 'esbuild', // 'esbuild' | 'rolldown' | 'rspack'
production: true,
sourcemap: false,
// merged with the .smartconfig.json in the cwd; see "Third-Party Notices"
thirdPartyNotices: { supplements: [] }
}
);
Source maps remain enabled by default. Set sourcemap: false for a bundle that
must generate neither an external .map file nor a final external sourceMappingURL reference.
Disabled programmatic and custom builds also remove stale destination maps.
Each bundler runs in a separate child process via smartspawn.ThreadSimple, keeping the main process clean and isolated from bundler-specific dependencies.
HtmlHandler Class
Process and optionally minify HTML files:
import { HtmlHandler } from '@git.zone/tsbundle';
const htmlHandler = new HtmlHandler();
await htmlHandler.processHtml({
from: './html/index.html',
to: './dist/index.html',
minify: true
});
AssetsHandler Class
Copy static assets between directories:
import { AssetsHandler } from '@git.zone/tsbundle';
const assetsHandler = new AssetsHandler();
await assetsHandler.processAssets({
from: './assets',
to: './dist/assets'
});
Base64TsOutput Class
Generate TypeScript files with base64-encoded content for embedding:
import { Base64TsOutput } from '@git.zone/tsbundle';
const output = new Base64TsOutput(process.cwd());
output.addFile('bundle.js', bundleBuffer);
await output.addIncludeFiles(['./html/**/*.html', { from: './assets/favicon.ico', to: 'favicon.ico' }]);
await output.writeToFile('./ts/embedded-bundle.ts', 200); // optional maxLineLength
CustomBundleHandler Class
Process multiple bundle configurations from .smartconfig.json:
import { CustomBundleHandler } from '@git.zone/tsbundle';
const handler = new CustomBundleHandler(process.cwd(), { keepTemp: false });
const hasConfig = await handler.loadConfig();
if (hasConfig) {
await handler.processAllBundles();
}
Embedding for Deno Compile
For single-executable scenarios with Deno:
tsbundle init
# Select "custom", set outputMode to "base64ts"
Config:
{
"@git.zone/tsbundle": {
"bundles": [
{
"from": "./ts_web/index.ts",
"to": "./ts/embedded-bundle.ts",
"outputMode": "base64ts",
"bundler": "esbuild",
"production": true,
"includeFiles": ["./html/index.html"],
"maxLineLength": 200
}
]
}
}
Then in your Deno app:
import { files } from './ts/embedded-bundle.ts';
// Decode and serve your embedded files
const bundle = files.find(f => f.path === 'bundle.js');
const html = files.find(f => f.path === 'index.html');
const bundleContent = atob(bundle.contentBase64);
const htmlContent = atob(html.contentBase64);
Project Structure Recommendations
your-project/
├── ts_web/ # Web bundle entry points
│ └── index.ts
├── ts/ # Library/node entry points
│ └── index.ts
├── html/ # HTML templates
│ └── index.html
├── assets/ # Static assets (images, fonts, etc.)
├── dist_bundle/ # Output for element/npm bundles
├── dist_serve/ # Output for website bundles
└── .smartconfig.json # tsbundle configuration
License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the LICENSE 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.