@git.zone/tsbundle
v3.7.0
Published
a multi-bundler tool supporting esbuild, rolldown, and rspack for painless bundling of web projects
Readme
@git.zone/tsbundle
A powerful multi-bundler tool supporting esbuild, rolldown, and rspack for painless bundling of web projects, plus single-file ESM bundles for Node.js.
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/tsbundleQuick Start
Interactive Setup
The easiest way to get started is with the interactive wizard:
tsbundle initThis 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:
tsbundleYour 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 |
| tsbundle notices --metafile <file> --working-directory <dir> --to <artifact> | Write third-party notices for a bundle another bundler built (see Notices for bundles built by other bundlers) |
The preset commands remain available for established package scripts and accept flags such as --production, --bundler, --platform, --sea, --sourcemap, --code-splitting, 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 |
| platform | "browser" | "node" | "browser" | Runtime the bundle runs on; "node" emits exactly one ESM file (see Node.js Platform) |
| sea | boolean | false | Build the main module of a Node.js single executable application: native addon loads go through @push.rocks/smartsea and <to>.smartsea.json is written beside the bundle (see SEA Mode) |
| 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) |
| codeSplitting | boolean | false | Split the bundle at its dynamic import()s into chunk files beside it (see Code Splitting) |
| 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 module that embeds the bundle, its artifacts and the included files as base64 strings, so a package can carry a web bundle inside its own code and serve it without reading files beside it:
// 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.
With third-party notices on, the module's notices are also written beside it as <to>.third-party-notices.txt and .json (for ts/bundled.ts: ts/bundled.ts.third-party-notices.txt and .json), byte for byte the copies embedded next to bundle.js, so a tool that packs the module into a binary or image can merge them into its own notices without decoding the module. They are published under the module's lock and rollback, and a build without notices removes them.
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 and writes them beside the module as <to>.third-party-notices.txt and .json. 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. A module that a package's browser field maps to false is replaced by an empty stub and contributes no code, so it is not listed either.
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/[email protected]"],
"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.
Notices for other tools: @git.zone/tsbundle/notices
Tools that ship npm code next to or around a bundle, such as a builder of Node.js single executable applications that also embeds native addon packages, resolve notices with the same rules through a separate entry point. It loads only the notices module, Node.js built-ins and @push.rocks/smartconfig, never the bundlers, TypeScript or the CLI:
import {
resolveThirdPartyNotices,
renderThirdPartyNoticePackageSections,
ThirdPartyNoticesError,
} from '@git.zone/tsbundle/notices';
const notices = await resolveThirdPartyNotices({
projectDirectory: process.cwd(),
// Package roots, for packages the tool knows by directory, such as a package cache without node_modules folders ...
packageDirectories: ['/home/me/.cache/packages/registry.npmjs.org/lit/3.3.3'],
// Package roots whose whole source tree the output contains, such as a native addon compiled from it.
compiledPackageDirectories: ['/home/me/project/node_modules/argon2'],
// ... and/or module files attributed through node_modules, as the bundlers pass them.
modulePaths: [],
supplements: [], // the calling tool's project supplements, reported as supplied by `project`
generator: '@git.zone/tssea',
});
const sections = renderThirdPartyNoticePackageSections(notices.packages); // lines, one section per packageFor packageDirectories and module paths, as for bundles, the license and notice files in the package root are collected. A native addon contains code compiled from sources whose licenses often live below the root, such as a vendored C library's argon2/LICENSE, so compiledPackageDirectories collects those files at every depth of the package, named by their path relative to the package root with / separators (argon2/LICENSE). The walk is deterministic, skips every node_modules directory and does not follow symbolic links to directories; a directory given in both options is read once, at every depth. Compiled packages are otherwise resolved like the others: the own package is skipped, supplements apply, and a package without any license text fails with ThirdPartyNoticesError. Which packages count as compiled - an addon package and the dependencies it compiles in - is the calling tool's decision.
Tools that combine the notices of several sources - a bundle's <bundle>.third-party-notices.json, the packages of the native addons a single executable application embeds, a runtime's platform packages - read and merge them with tsbundle's own rules:
import {
mergeThirdPartyNoticePackages,
parseThirdPartyNotices,
ThirdPartyNoticesFormatError,
} from '@git.zone/tsbundle/notices';
const bundleNotices = parseThirdPartyNotices(
await fs.readFile('dist/main.mjs.third-party-notices.json', 'utf8'),
'dist/main.mjs.third-party-notices.json', // names the document in errors
);
const packages = mergeThirdPartyNoticePackages([bundleNotices.packages, addonNotices.packages]);parseThirdPartyNotices(json, source?)accepts exactly the JSONrenderThirdPartyNoticesJson()writes:{ generator, packages }, each package{ name, version, license, files }with at least one file, each file{ name, origin, suppliedBy?, sha256, text }withsuppliedBypresent exactly fororigin: "supplement", and everyname@versiononce. Invalid JSON, a missing or mistyped field and any unknown field - another tool's notices format, for example - throwThirdPartyNoticesFormatErrornaming the source and the field path (packages[3].files[0].sha256 must be 64 lowercase hex digits).mergeThirdPartyNoticePackages(lists)returns one entry pername@version, sorted by name and version in code-unit order, with each file (origin, supplier, name, digest) listed once in the orderresolveThirdPartyNotices()uses; the result does not depend on the order of the lists, and the inputs are not modified. Onename@versionwith different licenses, or one file with two different texts, throwsThirdPartyNoticesFormatError.
Every package's own "@git.zone/tsbundle".thirdPartyNotices.supplements apply exactly as in a bundle, so a library that ships the text of a license-less dependency covers both its bundles and the executables that embed it. A package without text still fails with ThirdPartyNoticesError, whose missingPackages lists each one.
Notices for bundles built by other bundlers
A bundle that another bundler built - an Angular application, for example - gets notices in tsbundle's format from its esbuild metafile, so a tool that embeds it, such as @git.zone/tssea through thirdPartyNotices.include, merges them like any bundle's:
tsbundle notices \
--metafile ui/dist/app/stats.json \
--working-directory ui \
--to ui/dist/app/browser| Option | Meaning |
|--------|---------|
| --metafile <file> | The esbuild metafile the bundler wrote. Angular's application builder writes it as stats.json beside its browser/ directory with "statsJson": true (or ng build --stats-json). |
| --working-directory <dir> | The bundler's working directory (esbuild's absWorkingDir), which the metafile's keys are relative to; for Angular, the workspace root. |
| --to <artifact> | The bundle file or directory the notices accompany. It must exist; the command writes <artifact>.third-party-notices.txt and .json beside it (ui/dist/app/browser.third-party-notices.json). |
| --output-directory <dir> | Optional: the directory the metafile's output keys name files in, before the bundler wrote them to --to. Defaults to the working directory, where Angular's application builder puts them. |
Relative paths resolve against the directory the command runs in, and that directory is the project: the supplements of its .smartconfig.json apply, read with the same settings resolver as a build of that project ("@git.zone/tsbundle".thirdPartyNotices.supplements; enabled decides for bundles only, the command always writes notices), and its own package.json name is first-party.
- Packages: the inputs of every
outputsentry, resolved against the working directory, are attributed to their npm packages exactly like the modules of a tsbundle build, with the same supplements from bundled packages and the same failure: a package without license text fails the command withThirdPartyNoticesError, naming every such package. The top-levelinputsalso list modules that tree shaking removed, so they are not read; a module abrowserfield disables ((disabled):<path>) contributes no code and is not listed. - Virtual modules: an input in another esbuild namespace (
<namespace>:<path>, such as Angular'sangular:styles/component:css;…stylesheets orcss-inline-fonts:https://…) is no file and counts as first-party. A namespaced input whose path names anode_modulesdirectory cannot be attributed to a package root and fails the command. - Stale metafiles: when
--tois a directory, every.js,.mjsand.cssfile below it must be an output of the metafile (output keys resolved against the working directory and taken relative to--output-directory, files relative to--to); otherwise the command fails and lists the files the metafile does not know, because a stale or partial metafile would under-report. Outputs that were never written, such as the component stylesheets Angular inlines into its JavaScript, are fine. - Copied files: files the bundler copies verbatim - Angular's
assets, for example - never appear in a metafile, so the command cannot list their packages. Their notices are the project's responsibility: a file from a package whose code is also in the bundle is covered by that package's entry (and its supplement, if it needs one); any other copied file is first-party, or the project ships its license text itself. - Failure: the pair an earlier run left is removed before the command starts, so a failed run leaves no stale notices behind.
Programmatically, getEsbuildMetafileModulePaths(metafile, workingDirectory) from @git.zone/tsbundle/notices returns the module files of one metafile under these rules, ready for resolveThirdPartyNotices({ modulePaths }); a build with several metafiles calls it once for each and combines the results. tsbundle's own esbuild builds attribute their modules through it.
Notices for code outside npm
Tools that ship code from other ecosystems - the crates of a Rust binary, a native library, a statically linked C runtime - write their notices in the same format, beside the artifact under the same suffixes (getThirdPartyNoticesPaths(), thirdPartyNoticesJsonSuffix, thirdPartyNoticesTextSuffix), so one parser and one merge serve every artifact. @git.zone/tsrust, for example, writes <binary>.third-party-notices.json and .txt beside each Rust binary.
A package outside npm is named with its ecosystem as a prefix, so it never collides with an npm package and stays recognizable in a merged list; npm packages keep their plain npm name:
| name | Code from |
|--------|-----------|
| cargo:<crate> | A Rust crate, e.g. cargo:serde |
| native:<lib> | A native library built or vendored outside a package manager, e.g. native:libsodium |
| rust:std, rust:compiler-builtins | The Rust standard library and compiler built-ins linked into a binary |
| runtime:musl, runtime:glibc, runtime:gcc, runtime:<name> | A runtime linked into or shipped with the artifact |
The prefixes are a convention between producers, not part of the parser: parseThirdPartyNotices() only requires name and version to be non-empty strings. mergeThirdPartyNoticePackages() keys packages by name@version, so the same crate from two binaries is listed once with its files combined, and one name@version with two different licenses, or one file with two different texts, throws ThirdPartyNoticesFormatError.
createThirdPartyNoticeFile() builds a file entry from the bytes of a license or notice file with the rules resolveThirdPartyNotices() uses, so every producer computes the same digest and text:
import {
createThirdPartyNoticeFile,
renderThirdPartyNoticePackageSections,
renderThirdPartyNoticesJson,
} from '@git.zone/tsbundle/notices';
const licenseFile = createThirdPartyNoticeFile({
name: 'LICENSE-MIT', // path relative to the crate root, with `/` separators
origin: 'package',
content: await fs.readFile(path.join(crateDirectory, 'LICENSE-MIT')), // a Buffer or Uint8Array
});
const packages = [{ name: 'cargo:serde', version: '1.0.228', license: 'MIT OR Apache-2.0', files: [licenseFile] }];sha256is the hex SHA-256 of the bytes as given;textis their UTF-8 decoding without a leading byte order mark, with CRLF and CR line endings turned into LF.origin: 'supplement'needs a non-emptysuppliedBy,origin: 'package'refuses one, andnamemust be a non-empty string; an entryparseThirdPartyNotices()would refuse throwsThirdPartyNoticesFormatErrorinstead.renderThirdPartyNoticesText()introduces its sections as the contents of a JavaScript bundle; a tool that ships another kind of artifact writes its own header followed byrenderThirdPartyNoticePackageSections(), and the JSON withrenderThirdPartyNoticesJson().
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.
In a platform: "node" build the esbuild backend inlines workers instead of emitting them; see Node.js Platform.
Node.js Platform
platform: "node" - --platform node for the presets, the same option for TsBundle.build() - bundles for Node.js and emits exactly one ESM file at to, plus its source map, its third-party notices and the included files when enabled; never a chunks/ directory. Every dependency is bundled; Node.js built-ins stay imports. The file runs with plain node and is the main module of a Node.js single executable application (SEA, node --build-sea with "mainFormat": "module"), which @git.zone/tssea builds from it. Inside a SEA, import and require load Node.js built-ins only and import.meta.url is the executable, so the bundle must carry everything else itself.
- CommonJS dependencies call
requirefor built-ins. Esbuild gets a module-scopedrequirefrom a banner,import { createRequire as __tsbundleCreateRequire } from 'node:module'; const require = __tsbundleCreateRequire(import.meta.url);, placed after your ownbannerso a shebang stays on the first line; a bundled module's own top-levelconst require = createRequire(import.meta.url)keeps working, because esbuild renames it. Rolldown injects its owncreateRequire. - Workers constructed as
new Worker(new URL('./worker.ts', import.meta.url), options)are bundled by esbuild in memory - one ESM file each, Node.js platform and banner included, source map inline when source maps are on - and inlined: the call becomesnew Worker(<source>, { ...options, eval: true }). Nested workers are inlined recursively, a worker reused by several parents is bundled once, and cyclic worker graphs reject the build. Rolldown does not inline workers; aplatform: "node"rolldown build that constructs one fails with an error that names esbuild. - Refused combinations: rspack, which always splits at dynamic imports, and
codeSplitting: truefail before a bundler starts, each with an error naming the supported combination. A build whose output would hold anything besides the one JavaScript file and its map fails too. - Not provided:
__dirnameand__filenamestay undefined in the ESM output, so CommonJS code that uses them throws at run time. Inside a SEA, worker orchild_process.fork()paths computed at run time (new Worker(path.join(__dirname, 'worker.js')),fork(script)) and file reads relative toimport.meta.urlresolve next to the executable, outside the bundle; only the staticnew URL('<specifier>', import.meta.url)worker form is inlined.
{
"@git.zone/tsbundle": {
"bundles": [
{
"from": "./ts/index.ts",
"to": "./dist_node/main.js",
"bundler": "esbuild",
"platform": "node",
"production": true
}
]
}
}Name the output .mjs, or .js inside a package with "type": "module", so plain node loads it as an ES module; a SEA main declares its format itself.
SEA Mode: Native Addons for Single Executable Applications
Inside a Node.js single executable application require() loads built-ins only, so a native addon (.node file) must be embedded as a SEA asset and opened with process.dlopen. sea: true (--sea for the presets) makes the bundle the main module of such an application: every native addon load becomes loadAddon('<id>') of @push.rocks/smartsea, and <to>.smartsea.json beside the bundle tells the SEA build tool, @git.zone/tssea, which addons to embed.
{
"@git.zone/tsbundle": {
"bundles": [
{ "from": "./ts/index.ts", "to": "./dist_node/main.mjs", "platform": "node", "sea": true, "production": true }
]
}
}Requirements:
platform: "node", bundleresbuildand output modebundle; every other combination fails before a bundler starts, with an error naming the supported one. The rewritten loads importloadAddonfrom@push.rocks/smartseaas the bundled project resolves it, so the project declares@push.rocks/smartseaas a dependency; without it the build fails with an error saying so. Its major version must equal the one tsbundle depends on (LAYOUT_INCOMPATIBLEotherwise).The bundle runs only inside a SEA. Outside one,
loadAddonthrowsNOT_IN_SEA; nothing falls back to the file system.Rewritten loads - in the project's code, its dependencies and the Node.js workers esbuild inlines:
| Load in the source | Addon id | |---|---| |
require('node-gyp-build')(dir), or a constant fromrequire('node-gyp-build')/import x from 'node-gyp-build'that is only ever called |<owner>@<version>:node-gyp-build[:<dir relative to the owner root>]| |require('bindings')('<name>'),bindings({ bindings: '<name>' })orbindings()(meaningbindings.node), called directly or through a constant like node-gyp-build |<owner>@<version>:bindings:<name>.node(.nodeappended as bindings does) | |require('./<path>.node'),require('../<path>.node'), onrequireor oncreateRequire(import.meta.url)/createRequire(__filename)|<owner>@<version>:file:<path relative to the owner root>| |require('<package>/<path>.node')|<owner>@<version>:package:<package>/<path>.node|node-gyp-build's directory must be computable at build time:
__dirname,__filename, string literals,+, template literals,path.join,path.resolvewith an absolute argument,path.dirname,fileURLToPath(import.meta.url),fileURLToPath(new URL('<literal>', import.meta.url)), and constants declared once with such a value. The load sites stay lazy: arequire('./x.node')insidetrystill throws there, asADDON_NOT_EMBEDDED, when the executable embeds no such addon.Refused loads fail the build at
file:line:column, with what SEA mode supports: any other use ofnode-gyp-buildorbindings(load.path(dir), passing the loader on, other bindings options, a subpath import), a node-gyp-build directory known only at run time, a.nodepath computed at run time,import/import()/require.resolve()of a.nodefile,require()fromcreateRequire()of another location, absolute.nodepaths,process.dlopen()(except in@push.rocks/smartseaitself), and a package entry point (main/exports) that resolves to a.nodefile - the napi-rs per-platform package form, which SEA mode does not support yet; support comes with@git.zone/tssea. Arequire(variable)without a.nodesuffix is left as it is: inside a SEA it loads built-ins only.
The bundle references file: <to>.smartsea.json
Written in SEA mode on every build, also without addons, in @push.rocks/smartsea's canonical format (ISeaBundleReferences, serialized with serializeBundleReferences, read with parseBundleReferences from @push.rocks/smartsea/layout). It is a build intermediate for the SEA build tool and is never embedded. Publication writes it with the bundle, under the same lock and rollback, derived for the published file name and bytes; a build without SEA mode removes a stale one, and an included file may not take its path. This is the contract @git.zone/tssea implements against:
layoutVersion: the@push.rocks/smartseaversion tsbundle wrote the file with.runtimes: the version of every@push.rocks/smartseapackage copy whose code is in the bundle, inlined workers included; sorted, without duplicates, empty when no addon is loaded and the project does not bundle smartsea.bundle:file, the bundle's file name, andsha256, the SHA-256 of its published bytes.addons: one entry per addon id, sorted by id:idandparts: the addon id (formatAddonId(parts)).- The owner (
parts.owner) is the package the load site belongs to: the nearest directory at or above the directory of the module holding the load whosepackage.jsonhas both anameand aversion. Apackage.jsonwithout them - a{ "type": "module" }scope file indist/esm/, for example - is skipped. Modules are taken at their real paths, so pnpm's symbolic links resolve to the package in its store. packageDirectory: the owner's root, the absolute real path of the directory holding thatpackage.json, on the build host.- node-gyp-build
directory: the directory passed to node-gyp-build, relative topackageDirectory,/-separated; absent when it ispackageDirectoryitself. A directory outside the owner root fails the build.packageDirectory/directoryis the directory node-gyp-build searches at run time (build/Release,build/Debug,prebuilds/<platform>-<arch>/). - bindings
binding: the file name bindings searches for; its search starts atpackageDirectory. tsbundle checks that bindings' own module root for the load site (the nearest directory above the module holding apackage.jsonor anode_modulesdirectory) ispackageDirectory, and fails the build when it is not. - file
path: the.nodefile relative topackageDirectory,/-separated; a path outside the owner root fails the build. - package
specifier: the specifier as written, resolved frompackageDirectory. sites: the modules holding the load sites, as esbuild names its inputs: paths relative to the project directory (the build's working directory),/-separated, sorted. A load site in a module that reaches the output only through an inlined worker is listed like any other.- Ids are recorded whether or not the file exists on the build host: per-target availability is tssea's decision. A
require('./x.node')alternative whose addon is not embedded throwsADDON_NOT_EMBEDDEDwhere the original would have thrown.
Code Splitting
Esbuild and rolldown inline every dynamic import() into the one bundle file by default. Set codeSplitting: true on a bundle - --code-splitting for the presets, the same option for TsBundle.build() - to split it at its dynamic imports instead: each dynamically imported module, together with the modules it shares with the rest of the bundle, becomes a chunk file that is loaded when the import runs, so the initial load carries only the code it executes.
The chunks are published below chunks/<namespace>/[name]-[hash].js beside the bundle, the namespace derived from the bundle's file name, and the bundle loads them by relative URL. Whatever serves the bundle must therefore serve its chunks/ directory next to it. base64ts output embeds the chunks with the bundle, and the third-party notices list the packages of every chunk.
Rspack always splits at dynamic imports, with or without the option. Esbuild documents its code splitting as a work in progress with a known ordering issue for imports across chunks (esbuild#399), so code whose side effects depend on module evaluation order, such as custom element registration, should be tested on the split build. Callers of TsBundle.build() that do not set the option, @git.zone/tstest among them, keep getting one file.
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'
platform: 'browser', // 'browser' (default) | 'node': one ESM file; see "Node.js Platform"
sea: false, // true with platform 'node': a single executable application main; see "SEA Mode"
production: true,
sourcemap: false,
codeSplitting: false, // true: chunks at dynamic imports; see "Code Splitting"
// 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.
A failed build rejects with an Error whose message carries the bundler's diagnostics as plain text, at most 16,384 characters: esbuild errors as file:line:column: text lines, rolldown and rspack messages without terminal colour codes, for example Bundle build failed with exit code 1:\nsrc/entry.ts:2:23: Unexpected ";". The child process still prints the failure to the terminal.
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 a static assets directory, including its subdirectories, replacing the target directory:
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 maxLineLengthCustomBundleHandler 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 a Bundle in a Package
base64ts output turns a bundle and its included files into a TypeScript module, so a package can serve a web UI from its own code:
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 server code:
import { files } from './embedded-bundle.js';
// Decode and serve the embedded files
const bundle = files.find((file) => file.path === 'bundle.js');
const html = files.find((file) => file.path === 'index.html');
const bundleContent = Buffer.from(bundle.contentBase64, 'base64');
const htmlContent = Buffer.from(html.contentBase64, 'base64').toString('utf8');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 configurationLicense 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.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 [email protected].
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.
