Transpiler - BunDocumentation Index Search...⌘KInstall Bun Search...Navigation Interop & Tooling TranspilerRuntimePackage ManagerBundlerTest RunnerGuidesReferenceBlogFeedback:first-child]:!hidden peer-[.is-custom]:[&>:first-child]:sm:!hidden peer-[.is-custom]:[&>:first-child]:md:!hidden peer-[.is-custom]:[&>:first-child]:lg:!hidden peer-[.is-custom]:[&>:first-child]:xl:!hidden">Get StartedWelcome to BunInstallationQuickstartTypeScriptTypeScript 6 and 7bun initbun createCore RuntimeBun RuntimeWatch ModeDebuggingREPLbunfig.tomlFile & Module SystemFile TypesModule ResolutionJSXAuto-installPluginsFile System RouterHTTP serverServerRoutingCookiesTLSError HandlingMetricsNetworkingFetchWebSocketsTCPUDPDNSData & StorageCookiesFile I/OStreamsBinary DataArchiveSQLSQLiteS3RedisConcurrencyWorkersProcess & SystemEnvironment VariablesShellSpawnWebViewCronInterop & ToolingNode-APIFFIC CompilerTranspilerUtilitiesCSRF ProtectionSecretsConsoleTOMLYAMLMarkdownJSON5JSONLHTMLRewriterImageHashingGlobSemverColorUtilsStandards & CompatibilityGlobalsBun APIsWeb APIsNode.js CompatibilityContributingRoadmapBenchmarkingContributingBuilding WindowsBindgenLicense On this page.transformSync().transform().scan().scanImports()ReferenceInterop & ToolingTranspiler Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_n4ctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed"> *]:[overflow-wrap:anywhere]"> Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_1cctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed"> Bun exposes its internal transpiler via the Bun.Transpiler class. To create an instance of Bun’s transpiler:
Yes NoSuggest editsRaise issueC CompilerPreviousCSRF ProtectionNext⌘I xgithubdiscordyoutubePowered byThis documentation is built and hosted on Mintlify, a developer documentation platform
Fetch the complete documentation index at: /docs/llms.txt
Use this file to discover all available pages before exploring further.
Skip to main contentBun home pageUse Bun’s transpiler to transpile JavaScript and TypeScript code
const transpiler = new Bun.Transpiler({
loader: "tsx", // "js" | "jsx" | "ts" | "tsx"
});
.transformSync()
Transpile code synchronously with the .transformSync() method. Modules are not resolved and the code is not executed. The result is a string of vanilla JavaScript code.
transpile.tsoutputconst transpiler = new Bun.Transpiler({
loader: 'tsx',
});
const code = `
import * as whatever from "./whatever.ts"
export function Home(props: {title: string}){
return {props.title}
;
}`;
const result = transpiler.transformSync(code);
To override the default loader specified in the new Bun.Transpiler() constructor, pass a second argument to .transformSync().
transpiler.transformSync("hi!", "tsx");
Nitty gritty
When .transformSync is called, the transpiler is run in the same thread as the currently executed code.If a macro is used, it will be run in the same thread as the transpiler, but in a separate event loop from the rest of your application. Currently, globals between macros and regular code are shared, which means it is possible (but not recommended) to share states between macros and regular code. Attempting to use AST nodes outside of a macro is undefined behavior. .transform() The transform() method is an async version of .transformSync() that returns a Promise.const transpiler = new Bun.Transpiler({ loader: "jsx" });
const result = await transpiler.transform("hi!");
console.log(result);
Unless you’re transpiling many large files, you should probably use Bun.Transpiler.transformSync. The cost of the threadpool will often take longer than actually transpiling code.
await transpiler.transform("hi!", "tsx");
Nitty gritty
The .transform() method runs the transpiler in Bun’s worker threadpool, so if you run it 100 times, it will run it across Math.floor($cpu_count * 0.8) threads, without blocking the main JavaScript thread.If your code uses a macro, it will potentially spawn a new copy of Bun’s JavaScript runtime environment in that new thread. .scan() The Transpiler instance can also scan some source code and return a list of its imports and exports, plus additional metadata about each one. Type-only imports and exports are ignored. example.tsoutputconst transpiler = new Bun.Transpiler({
loader: "tsx",
});
const code = `
import React from 'react';
import type {ReactNode} from 'react';
const val = require('./cjs.js')
import('./loader');
export const name = "hello";
`;
const result = transpiler.scan(code);
Each import in the imports array has a path and kind. Bun categories imports into the following kinds:
import-statement: import React from 'react'
require-call: const val = require('./cjs.js')
require-resolve: require.resolve('./cjs.js')
dynamic-import: import('./loader')
import-rule: @import 'foo.css'
url-token: url('./foo.png')
.scanImports()
For performance-sensitive code, you can use the .scanImports() method to get a list of imports. It’s faster than .scan() (especially for large files) but marginally less accurate due to some performance optimizations.
example.tsresultsconst transpiler = new Bun.Transpiler({
loader: "tsx",
});
const code = `
import React from 'react';
import type {ReactNode} from 'react';
const val = require('./cjs.js')
import('./loader');
export const name = "hello";
`;
const result = transpiler.scanImports(code);
Reference
See Typescript Definitionstype Loader = "jsx" | "js" | "ts" | "tsx";
interface TranspilerOptions {
// Replace key with value. Value must be a JSON string.
// { "process.env.NODE_ENV": "\"production\"" }
define?: Recordstring, string>,
// Default loader for this transpiler
loader?: Loader,
// Default platform to target
// This affects how import and/or require is used
target?: "browser" | "bun" | "node",
// Specify a tsconfig.json file as stringified JSON or an object
// Use this to set a custom JSX factory, fragment, or import source
// For example, if you want to use Preact instead of React. Or if you want to use Emotion.
tsconfig?: string | TSConfig,
// Replace imports with macros
macro?: MacroMap,
// Specify a set of exports to eliminate
// Or rename certain exports
exports?: {
eliminate?: string[];
replace?: Recordstring, string>;
},
// Whether to remove unused imports from transpiled file
// Default: false
trimUnusedImports?: boolean,
// Whether to enable a set of JSX optimizations
// jsxOptimizationInline ...,
// Experimental whitespace minification
minifyWhitespace?: boolean,
// Whether to inline constant values
// Typically improves performance and decreases bundle size
// Default: true
inline?: boolean,
}
// Map import paths to macros
interface MacroMap {
// {
// "react-relay": {
// "graphql": "bun-macro-relay/bun-macro-relay.tsx"
// }
// }
[packagePath: string]: {
[importItemName: string]: string,
},
}
class Bun.Transpiler {
constructor(options: TranspilerOptions)
transform(code: string, loader?: Loader): Promisestring>
transformSync(code: string, loader?: Loader): string
scan(code: string): {exports: string[], imports: Import}
scanImports(code: string): Import[]
}
type Import = {
path: string,
kind:
// import foo from 'bar'; in JavaScript
| "import-statement"
// require("foo") in JavaScript
| "require-call"
// require.resolve("foo") in JavaScript
| "require-resolve"
// Dynamic import() in JavaScript
| "dynamic-import"
// @import() in CSS
| "import-rule"
// url() in CSS
| "url-token"
// The import was injected by Bun
| "internal"
// Entry point (not common)
| "entry-point-build"
| "entry-point-run"
}
const transpiler = new Bun.Transpiler({ loader: "jsx" });
See all 90 linesWas this page helpful?
Transpiler - Bun,AI智能索引,全网链接索引,智能导航,网页索引
- Use Bun