日本語

Converting TypeScript to JavaScript with Bun.Transpiler

​​Bun​Node.js,TypeScript

Bun.Transpiler in Bun is a class that takes TypeScript code as a string and returns a JavaScript string with the types removed. It does not bundle files together like a bundler does. It converts one file at a time. You can use it when you want to turn a TypeScript script into a .js file that runs in Node.js or a browser without installing a build tool, or when you want to include code conversion in your own script.

In my test environment, simply converting the .ts files in src/ to .js as they were did not run in Node.js. It failed at two points: the import extensions, and imports that only bring in types. Rewriting the import extensions myself and removing the type-only imports with trimUnusedImports: true made it run. When converting a lot of code, waiting on transform() calls with Promise.all() finished faster than transformSync(). (These numbers come from repeatedly converting the same code in memory.)

Note

The test environment was Ubuntu 24.04 (x86_64, 4 CPUs) with Bun 1.4.4. I ran the converted .js files with Node.js 22.23.5. To keep Bun's behavior from changing with environment variables, I ran everything with env -i, which leaves almost no environment variables set. I replaced the working directory path shown in errors with /path/to/app. I did not test JSX (loader: "tsx"), decorators, the tsconfig option, macros, or Windows and macOS. I checked the official documentation against the source files at the tag used for testing (bun-v1.4.4) on GitHub.

Basic usage of Bun.Transpiler

Create an instance with new Bun.Transpiler({ loader: "ts" }), then pass a code string to transformSync(). According to the official documentation, the Transpiler does not resolve modules or run code, and it returns the result as a JavaScript string (transformSync description in the official docs). For loader, specify one of "js", "jsx", "ts", or "tsx".

I converted the following sample.ts. It includes an interface, an enum, a constructor parameter property with private readonly, satisfies, and ! (non-null assertion).

ts
import { readFileSync } from "node:fs";
import type { Stats } from "node:fs";
import { helper } from "./helper.ts";

interface User {
  id: number;
  name: string;
}

enum Role {
  Admin,
  Member,
}

class Account {
  constructor(private readonly user: User, public role: Role = Role.Member) {}
  label(): string {
    return `${this.user.name} (${Role[this.role]})`;
  }
}

const size = (s: Stats): number => s.size;
const users = [{ id: 1, name: "neko" }] satisfies User[];
const first = users[0]!;
console.log(new Account(first, Role.Admin).label(), helper as unknown as string);

The conversion script is three lines.

ts
const transpiler = new Bun.Transpiler({ loader: "ts" });
const code = await Bun.file("sample.ts").text();
console.log(transpiler.transformSync(code));

This is the output of bun t1-basic.ts.

js
import { readFileSync } from "node:fs";
import { helper } from "./helper.ts";
var Role;
((Role) => {
  Role[Role["Admin"] = 0] = "Admin";
  Role[Role["Member"] = 1] = "Member";
})(Role ||= {});

class Account {
  user;
  role;
  constructor(user, role = 1 /* Member */) {
    this.user = user;
    this.role = role;
  }
  label() {
    return `${this.user.name} (${Role[this.role]})`;
  }
}
const size = (s) => s.size;
const users = [{ id: 1, name: "neko" }];
const first = users[0];
console.log(new Account(first, 0 /* Admin */).label(), helper);

Type annotations, interfaces, import type, satisfies, !, and as were removed. The enum became object code that works at runtime, and references such as Role.Admin were replaced with values like 0 /* Admin */. The constructor parameter properties became class fields and assignment statements.

On the other hand, the unused readFileSync import and the ./helper.ts extension were left as they were. These two points matter later when running the output in Node.js.

Type errors pass through, syntax errors throw

The Transpiler does not type-check. Code with type mismatches, such as const n: number = "not a number";, was converted as is.

js
const n = "not a number";
console.log(n);

When there is a syntax error, transformSync() throws an exception. The following checks what is thrown when const x: number = ; is passed in.

ts
const t = new Bun.Transpiler({ loader: "ts" });
try { t.transformSync(`const x: number = ;`); } catch (e: any) {
  console.log(Object.keys(e), e.message, JSON.stringify(e.position), e.level);
  console.log(e instanceof Error);
}
text
[] Unexpected ; {"lineText":"const x: number = ;","file":"input.ts","namespace":"file","line":1,"column":19,"length":1,"offset":18} error
true

The thrown value is a BuildMessage, and instanceof Error returned true. As the leading [] in the output shows, Object.keys() lists nothing. However, message contained the error text, and position contained the line number and the text of the line with the error. position.file is "input.ts", so if you want to show which file has the error, add the path of the file you are converting yourself.

Changing the output with trimUnusedImports, define, and minifyWhitespace

The options you can pass to the constructor are listed in the official reference. I tested three of them that change the output when converting TypeScript to JavaScript. This is the code I converted:

ts
import { readFileSync } from "node:fs";
import { helper } from "./helper.ts";
// Debug log
const DEBUG: boolean = process.env.NODE_ENV !== "production";
if (DEBUG) {
  console.log("debug", helper);
}
export const add = (a: number, b: number): number => a + b;

This is the output without options.

js
import { readFileSync } from "node:fs";
import { helper } from "./helper.ts";
const DEBUG = true;
if (DEBUG) {
  console.log("debug", helper);
}
export const add = (a, b) => a + b;

The comment was removed, and process.env.NODE_ENV !== "production" was replaced with true. I explain why in the next section.

With trimUnusedImports: true, the unused readFileSync import was removed. According to the official documentation, the default for this option is false.

js
import { helper } from "./helper.ts";
const DEBUG = true;
...

With define: { "process.env.NODE_ENV": '"production"' }, process.env.NODE_ENV was treated as "production", and DEBUG became false. The value is written as JSON, so for a string value you pass it with the quotes included, like '"production"'. Adding minifyWhitespace: true also removed the spaces and line breaks.

js
import{readFileSync}from"node:fs";import{helper}from"./helper.ts";const DEBUG=false;if(DEBUG){console.log("debug",helper)}export const add=(a,b)=>a+b;

The type definitions mark minifyWhitespace as "Experimental" (TranspilerOptions in bun-types).

process.env.NODE_ENV becomes the value at conversion time

Since the conversion without options replaced process.env.NODE_ENV !== "production" with true, I converted code that puts process.env.NODE_ENV and process.env.HOME side by side.

ts
const t = new Bun.Transpiler({ loader: "ts" });
console.log(t.transformSync(`console.log(process.env.NODE_ENV, process.env.HOME, process.env.NODE_ENV === "production");`));

These are the outputs when running the conversion script with bun t3-nodeenv.ts, and when running it with NODE_ENV=production set.

text
$ bun t3-nodeenv.ts
console.log("development", process.env.HOME, false);

$ env NODE_ENV=production bun t3-nodeenv.ts
console.log("production", process.env.HOME, true);

process.env.HOME was left as is, but process.env.NODE_ENV was replaced with a string. Without NODE_ENV set, it becomes "development"; when set, it becomes that value. In other words, the contents of the output .js depend on the NODE_ENV value when you run the conversion script.

If you convert code that switches its behavior based on NODE_ENV at runtime, be careful with this substitution. If you want the conversion result to be the same every time, specify the value explicitly with define, as in the previous section.

Converting .ts files in a folder to .js and running them in Node.js

I used the Transpiler to convert the TypeScript files in src/ to .js files in dist/, then ran them with Node.js 22. I placed the following three files in src/. In math.ts, the type-only Item is imported with a normal import, not import type.

ts
// src/types.ts
export interface Item {
  name: string;
  price: number;
}

// src/math.ts
import { Item } from "./types.ts";

export function total(items: Item[]): number {
  return items.reduce((sum, item) => sum + item.price, 0);
}

// src/index.ts
import type { Item } from "./types.ts";
import { total } from "./math.ts";

const items: Item[] = [
  { name: "かつおぶし", price: 300 },
  { name: "ねこじゃらし", price: 450 },
];
console.log(`合計: ${total(items)}円`);

Plain conversion stops at the import extensions

At first, I made a script that finds files with Bun.Glob, converts them, and writes them out.

ts
// Convert .ts in src/ to .js in dist/
const transpiler = new Bun.Transpiler({ loader: "ts" });
for await (const path of new Bun.Glob("**/*.ts").scan("src")) {
  const code = await Bun.file(`src/${path}`).text();
  const js = transpiler.transformSync(code);
  const out = `dist/${path.replace(/\.ts$/, ".js")}`;
  await Bun.write(out, js);
  console.log(`src/${path} -> ${out} (${js.length}文字)`);
}
text
$ bun build.ts
src/index.ts -> dist/index.js (157文字)
src/math.ts -> dist/math.js (127文字)
src/types.ts -> dist/types.js (0文字)

types.ts contains only types, so the output file was empty. I put a package.json containing only {"type":"module"} in dist/ and ran node dist/index.js. It stopped with an error (I omitted the stack trace and replaced the path).

text
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/path/to/app/dist/math.ts' imported from /path/to/app/dist/index.js

This happened because dist/index.js still contained import { total } from "./math.ts";. The Transpiler does not resolve modules, so it does not rewrite import paths either.

Fixing the extensions leads to a failure on the type-only import

Next, I used scanImports() to get the import paths from the converted code, and replaced those that start with . and end with .ts with .js. scanImports() is a method that returns the list of imports in the code (scanImports description in the official docs).

ts
// Convert .ts in src/ to .js in dist/, and also rewrite the extensions of relative imports to .js
const transpiler = new Bun.Transpiler({ loader: "ts" });
for await (const path of new Bun.Glob("**/*.ts").scan("src")) {
  let js = transpiler.transformSync(await Bun.file(`src/${path}`).text());
  for (const { path: spec } of transpiler.scanImports(js)) {
    if (spec.startsWith(".") && spec.endsWith(".ts")) {
      js = js.replaceAll(`"${spec}"`, `"${spec.slice(0, -3)}.js"`);
    }
  }
  await Bun.write(`dist/${path.replace(/\.ts$/, ".js")}`, js);
}

This time, a different error occurred (again, I omitted the stack trace and replaced the path).

text
$ cat dist/math.js
import { Item } from "./types.js";
export function total(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}
$ node dist/index.js
file:///path/to/app/dist/math.js:1
import { Item } from "./types.js";
         ^^^^
SyntaxError: The requested module './types.js' does not provide an export named 'Item'

The import type { Item } in index.ts was removed by the conversion, but the import { Item } in math.ts remained. Item is only used as a type, so it is not used in the converted code. As with readFileSync in the first section, the Transpiler without options does not remove unused imports. So it tried to import Item from the empty types.js, and stopped.

Running after adding trimUnusedImports

I changed the new Bun.Transpiler(...) line in the script above to new Bun.Transpiler({ loader: "ts", trimUnusedImports: true }) and converted again.

text
$ cat dist/index.js
import { total } from "./math.js";
const items = [
  { name: "かつおぶし", price: 300 },
  { name: "ねこじゃらし", price: 450 }
];
console.log(`合計: ${total(items)}円`);
$ cat dist/math.js
export function total(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}
$ node dist/index.js
合計: 750円

The Item import was removed from math.js, and the program ran to completion in Node.js.

Point

To run the .js files converted by Bun.Transpiler in Node.js, you need two things: rewrite the import extensions yourself, and use trimUnusedImports: true.

I also checked what trimUnusedImports does with an import that loads no names, such as import "./polyfill.ts";. I wanted to make sure that imports with side effects, where loading the file itself runs code, would not be removed.

ts
const t = new Bun.Transpiler({ loader: "ts", trimUnusedImports: true });
console.log(t.transformSync(`import "./polyfill.ts";\nimport { unused } from "./lib.ts";\nimport type { T } from "./types.ts";\nexport const x: T | null = null;`));
text
import"./polyfill.ts";
export const x = null;

The unused unused import and the import type were removed, and import "./polyfill.ts" was kept. (In this output, the space between import and the string was removed.)

Comparing the speed of transform and transformSync

Besides the synchronous transformSync(), the Transpiler has transform(), which returns a Promise. According to the official documentation, transform() runs on Bun's pool of worker threads and splits the work across Math.floor(number of CPUs × 0.8) threads. The documentation also recommends transformSync() unless you are converting many large files, because the cost of using the thread pool often exceeds the time spent on the conversion itself (transform description in the official docs).

So I measured the time for three call patterns:

  • Call transformSync() in a for loop, one after another
  • Call transform() many times and wait with Promise.all()
  • Call transform() and await each one in turn

There were two kinds of code. One was sample.ts from the first section (584 characters), converted 1,000 times. The other was about 48,000 characters of code made by concatenating 100 copies of sample.ts with the import lines removed, converted 200 times. I ran each five times and took the median. The test environment has 4 CPUs, so the formula in the official documentation gives 3 threads.

Horizontal bar chart comparing conversion times for the three call patterns. For both kinds of code, waiting on transform with Promise.all was the shortest
Conversion time (median of 5 runs). The upper and lower charts use different scales
Method 584 characters × 1,000 runs About 48k characters × 200 runs
transformSync() in sequence 23.7 ms 237.3 ms
transform() waited on with Promise.all() 13.3 ms 75.2 ms
transform() with each one awaited in turn 86.7 ms 325.7 ms

When I waited with Promise.all(), the large code took about a third of the time of transformSync(). Even for the small code, transform() was faster when 1,000 calls were sent together.

On the other hand, when I awaited each transform() call in turn, it was slower than transformSync() for both kinds of code. If you wait one at a time, only one conversion runs at once, and there is no benefit from running them in parallel on the thread pool. When I repeated the measurement once more, the order of the three methods did not change (small code: 31.1 ms, 15.6 ms, 98.8 ms; large code: 234.2 ms, 68.3 ms, 310.1 ms).

This measurement converted the same code repeatedly in memory and does not include file reading or writing time. Under these conditions, when converting many pieces of code, creating all the transform() Promises first and waiting with Promise.all() finished fastest.

​Posted by 86