Skip to content

Bundling + minifying

This example runs esbuild’s TypeScript transform, then Terser’s JavaScript minifier, inside a Knitting worker. Both tools are async APIs: after the esbuild transform resolves, minification does CPU-heavy work on that same worker. maxAwaitingTasks stops a worker from collecting too many such continuations while peers are idle.

Install Knitting, esbuild, and Terser with your runtime’s package manager:

Terminal window
npm install knitting esbuild terser
npm install --save-dev tsx
Terminal window
bun add knitting esbuild terser
Terminal window
deno add npm:knitting npm:esbuild npm:terser
bun.sh
bun src/run_bundling_and_minifying.ts

The program prints four minified snippets. Each input declares a number and logs it; the TypeScript annotation is removed, and Terser folds the constant into the console.log call.

With work stealing, an async task that reaches await leaves the worker’s immediate task queue, but its continuation still runs on that worker. Without a cap, the worker can claim more tasks while those transforms wait, then run all their minification steps one after another. The limit of 2 leaves additional calls in the shared queue for other workers to claim.

Start at 2 and measure your workload. Synchronous tasks do not use an awaiting slot, and a task holds its slot until its promise settles.

esbuild starts its platform binary. The Node example grants workers subprocess permission with run: true in the strict permission policy. This is a broad permission; use a narrower policy when the task code does not need subprocesses. Bun and Deno use the host runtime’s permission settings for thread workers.

run_bundling_and_minifying.ts
import { transform } from "esbuild";
import { minify } from "terser";
import { createPool, isMain } from "knitting";
export const build = async (source: string): Promise<string> => {
const { code } = await transform(source, { loader: "ts" });
return (await minify(code)).code ?? "";
};
if (isMain) {
const pool = createPool({
threads: 4,
permission: { mode: "strict", allowImport: true, run: true },
worker: { maxAwaitingTasks: 2 },
})({ build });
const sources = [33, 42, 73, 99].map((answer) =>
"const answer: number = " + answer + "; console.log(answer);"
);
try {
const output = await Promise.all(
sources.map((source) => pool.call.build(source)),
);
console.log(output);
} finally {
await pool.shutdown();
}
}