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
Section titled “Install”Install Knitting, esbuild, and Terser with your runtime’s package manager:
npm install knitting esbuild tersernpm install --save-dev tsxbun add knitting esbuild terserdeno add npm:knitting npm:esbuild npm:terserbun src/run_bundling_and_minifying.tsdeno run -A src/run_bundling_and_minifying.tsnpx tsx src/run_bundling_and_minifying.tsThe 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.
Why set maxAwaitingTasks
Section titled “Why set maxAwaitingTasks”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.
Node subprocess permission
Section titled “Node subprocess permission”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.
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(); }}