API reference/Transformer

Transformer

transformSync parses, transforms, and prints JavaScript and TypeScript source in a single call. It is exported by @swc-next/core, @swc-next/transformer, and the initialized @swc-next/core-browser package.

Signature

declare function transformSync(
  source: string,
  options?: TransformApiOptions | undefined | null,
): JsOutput;

source is the complete source text. Omitting options or passing null uses the defaults below. Transformation is synchronous.

Unlike parseSync, transformSync does not throw on syntax, semantic, configuration, or transform diagnostics; they are returned in output.diagnostics. Invalid option types or unknown option fields throw a TypeError.

Options encoding is not reentrant. Option getters and Proxy traps must not call transformSync again while it is encoding options.

TransformApiOptions

OptionTypeDefaultBehavior
filenamestringundefinedInfer language and source type, and identify the file in diagnostics, transforms, and source maps.
sourceMapbooleanfalseEmit a Source Map v3 object in output.map.
comments"all" | "none""all"Preserve or strip comments in the generated output.
parserParserConfig{}Override parser language, source type, comments, parentheses, or semantic checks.
transformerTransformerConfig{}Configure syntax lowering, TypeScript, JSX, decorators, modules, features, assumptions, and polyfills.
generatorGeneratorConfig{}Configure code generation formatting (asciiOnly, inlineScript, minify).

filename

Type: string

Used across the pipeline:

  • Infers parser.lang with langFromPath when parser.lang is omitted.
  • Infers parser.sourceType with sourceTypeFromPath when parser.sourceType is omitted.
  • Sets the sources entry in the generated source map when sourceMap is true (defaults to "input.js" when filename is omitted).
  • Supplies the source filename to transforms such as JSX development metadata unless overridden by transformer.filename.
import { transformSync } from "@swc-next/core";

const output = transformSync(
  "export const App = (props: { name: string }) => <div>{props.name}</div>;",
  { filename: "App.tsx" },
);

sourceMap

Type: boolean

Default: false

When true, output.map contains a Source Map v3 object. When false, output.map is omitted.

import { transformSync } from "@swc-next/core";

const { code, map } = transformSync("const answer: number = 42;", {
  filename: "answer.ts",
  sourceMap: true,
});

comments

Type: "all" | "none"

Default: "all"

Controls whether comments are emitted in the generated output. When parser.comments is omitted, this option also sets the parser comment mode, except when JSX, TypeScript-with-JSX, or AMD transforms are active: in those cases the parser still collects comments internally so directive pragmas can be read, while comments: "none" still strips comments from the output.

parser

Type: ParserConfig

Accepts the same fields as ParseApiOptions except errorRecovery: lang, sourceType, preserveParens, comments, and semanticErrors.

Explicit parser.lang and parser.sourceType values take precedence over values inferred from filename. When parser.semanticErrors is true, semantic early errors are appended to output.diagnostics; if any error diagnostics are reported during parsing or semantic checks, transformation and code generation are skipped.

transformer

Type: TransformerConfig

Configures syntax transforms. When omitted, TypeScript and JSX transforms are still enabled automatically based on the resolved lang.

generator

Type: GeneratorConfig

Accepts asciiOnly, inlineScript, and minify.

TransformerConfig

OptionTypeDefaultBehavior
filenamestringShared filenameOverride the filename used by transforms, including JSX development metadata.
targetstring | string[] | Record<Engine, string>NoneTarget environment for ECMAScript lowering.
typescriptboolean | TypeScriptConfigEnabled for "ts", "tsx", "dts"Strip and lower TypeScript syntax.
jsxboolean | JsxConfigEnabled for "jsx", "tsx"Transform JSX syntax.
decoratorsboolean | DecoratorConfigfalseTransform decorator syntax.
moduleModuleConfig"preserve"Convert ES modules to another module format or preserve them.
featuresPartial<Record<Feature, boolean>>{}Enable or disable individual syntax transforms.
assumptionsAssumptionsAll falseEnable Babel-compatible assumptions for smaller or faster output.
polyfillfalse | PolyfillConfigfalseInject core-js@3 polyfills for the target environment.

filename

Type: string

Overrides the top-level filename for transforms (such as JSX development __source metadata) without changing language inference or source map paths.

target

Type: "es2015" | ... | "es2026" | "esnext" | (string & {}) | string[] | Partial<Record<Engine, string>>

Selects the target environment for ECMAScript lowering:

  • ES edition: "es2015" through "es2026", or "esnext".
  • Browserslist query or query list: a single query string such as "> 0.5%, not dead" or an array of queries such as ["chrome 70", "chrome 120"].
  • Engine version map: minimum versions keyed by engine name ("chrome", "edge", "firefox", "safari", "ios", "opera", "samsung", "node", "deno", "electron", "ie", "android", "opera_mobile", "op_mini", "bb", "baidu", "kaios", "and_qq", "and_uc").
import { transformSync } from "@swc-next/core";

transformSync("const x = a ?? b;", { transformer: { target: "es2019" } });
transformSync("const x = a ?? b;", { transformer: { target: { node: "12" } } });
transformSync("const x = a?.b;", { transformer: { target: ["chrome 70", "chrome 120"] } });

target currently lowers ES2016–ES2022 and supported RegExp syntax. ES2015 and older syntax is not lowered, and "es3" / "es5" or invalid Browserslist queries return an error diagnostic in output.diagnostics.

typescript

Type: boolean | TypeScriptConfig

Default: enabled when the resolved lang is "ts", "tsx", or "dts". Pass false to keep TypeScript syntax in the output.

interface TypeScriptConfig {
  verbatimModuleSyntax?: boolean;
  jsxPragma?: string;
  jsxPragmaFrag?: string;
}
OptionTypeDefaultBehavior
verbatimModuleSyntaxbooleanfalsePreserve value imports and exports, and disable const enum inlining and removal.
jsxPragmastring"React.createElement"Classic JSX factory whose value import is preserved when JSX syntax is retained.
jsxPragmaFragstring"React.Fragment"Classic JSX fragment factory whose value import is preserved when JSX syntax is retained.

jsx

Type: boolean | JsxConfig

Default: enabled with the "automatic" runtime when the resolved lang is "jsx" or "tsx". Pass false to keep JSX syntax in the output.

JSX options target Babel 8; useSpread and useBuiltIns are not supported.

interface JsxConfig {
  runtime?: "classic" | "automatic";
  development?: boolean;
  sourceSelf?: boolean;
  importSource?: string;
  pragma?: string;
  pragmaFrag?: string;
  throwIfNamespace?: boolean;
  pure?: boolean;
  displayName?: boolean;
  refresh?: boolean | ReactRefreshConfig;
}

interface ReactRefreshConfig {
  refreshReg?: string;
  refreshSig?: string;
  emitFullSignatures?: boolean;
}
OptionTypeDefaultBehavior
runtime"classic" | "automatic""automatic"Choose the JSX runtime transform.
developmentbooleanfalseEmit development helpers (such as jsxDEV).
sourceSelfbooleanfalseAdd __source and __self props in development mode.
importSourcestring"react"Import source for the automatic runtime.
pragmastring"React.createElement"Element factory for the classic runtime.
pragmaFragstring"React.Fragment"Fragment factory for the classic runtime.
throwIfNamespacebooleantrueReport an error on XML namespace tags (<ns:tag />).
purebooleantrueAnnotate generated factory calls as pure.
displayNamebooleanfalseAdd displayName to createReactClass calls.
refreshboolean | ReactRefreshConfigfalseEnable React Refresh. Requires development: true and ES module source. true uses default options (refreshReg: "$RefreshReg$", refreshSig: "$RefreshSig$", emitFullSignatures: false).

decorators

Type: boolean | DecoratorConfig

Default: false

Pass true to enable "2023-11" decorators, or pass a configuration object:

interface DecoratorConfig {
  version?: "2023-11" | "legacy";
  metadata?: boolean;
}
OptionTypeDefaultBehavior
version"2023-11" | "legacy""2023-11"Select the decorator proposal version.
metadatabooleanfalseEmit Reflect.metadata design-type metadata. Requires version: "legacy"; enabling it with "2023-11" returns an error diagnostic.

module

Type: ModuleConfig

Default: "preserve"

Selects the module output format. Accepts a format shorthand string or an object discriminated by type:

type ModuleConfig =
  | "preserve"
  | "commonjs"
  | "amd"
  | "umd"
  | "systemjs"
  | ({ type: "preserve" } & PreserveModuleConfig)
  | ({ type: "commonjs" } & CommonJsModuleConfig)
  | ({ type: "amd" } & AmdModuleConfig)
  | ({ type: "umd" } & UmdModuleConfig)
  | ({ type: "systemjs" } & SystemJsModuleConfig);
import { transformSync } from "@swc-next/core";

transformSync("export const answer = 42;", {
  transformer: { module: "commonjs" },
});

transformSync('import foo from "foo";\nimport("bar");\nexport const x = foo;', {
  transformer: {
    module: { type: "commonjs", interop: "none", dynamicImport: "preserve" },
  },
});

Format-specific options:

FormatinteropdynamicImport
"preserve"——
"commonjs""babel" | "node" | "none" (default "babel")"transform" | "preserve" (default "transform")
"amd""babel" | "node" | "none" (default "babel")"transform" | "preserve" (default "transform")
"umd""babel" | "node" | "none" (default "babel")—
"systemjs"——

Passing an option unsupported by the chosen type (such as interop on "preserve") throws a TypeError.

  • interop: interoperability strategy for lowered default and namespace imports ("babel", "node", or "none").
  • dynamicImport: "transform" lowers dynamic import() calls for the target module format; "preserve" leaves them as import().

features

Type: Partial<Record<Feature, boolean>>

Per-feature overrides applied after target resolution. true enables a transform; false disables it even if target would otherwise enable it.

Supported feature names:

GroupFeature keys
ES2016"exponentiation-operator"
ES2017"async-to-generator", "async-generator-functions"
ES2018"object-rest-spread"
ES2019"optional-catch-binding"
ES2020"export-namespace-from", "nullish-coalescing-operator", "optional-chaining"
ES2021"logical-assignment-operators"
ES2022"class-static-block", "class-properties", "private-property-in-object"
RegExp"dotall-regex", "sticky-regex", "unicode-regex", "unicode-sets-regex"
import { transformSync } from "@swc-next/core";

const output = transformSync("a ?? b; a?.b;", {
  transformer: {
    target: "es2019",
    features: { "nullish-coalescing-operator": false },
  },
});

assumptions

Type: Assumptions

Babel-compatible assumptions. All fields are optional booleans and default to false:

interface Assumptions {
  constantSuper?: boolean;
  ignoreFunctionLength?: boolean;
  noDocumentAll?: boolean;
  objectRestNoSymbols?: boolean;
  privateFieldsAsProperties?: boolean;
  pureGetters?: boolean;
  setPublicClassFields?: boolean;
  setSpreadProperties?: boolean;
}

polyfill

Type: false | PolyfillConfig

Default: false

Injects core-js@3 polyfills based on the target environment. Only core-js@3 is supported (core-js@2 and regenerator-runtime are not supported).

interface PolyfillConfig {
  mode: "entry-global" | "usage-global";
  coreJs: string;
  target?: string | string[] | Partial<Record<Engine, string>>;
  proposals?: boolean;
  modules?: Record<string, boolean>;
}
OptionTypeDefaultBehavior
mode"entry-global" | "usage-global"Required"entry-global" expands manual side-effect import "core-js/..." statements for the target environment; "usage-global" injects core-js/modules/*.js imports based on detected API usage.
coreJsstringRequiredInstalled core-js 3.x version (such as "3.38" or "3.38.1"). Passing a non-3.x or invalid version returns an error diagnostic.
targetstring | string[] | Partial<Record<Engine, string>>Inherited from transformer.targetBrowserslist query, query list, or engine version map. ES edition strings (such as "es2020") are not supported for polyfills and return an error diagnostic; when no target is configured at either level, no automatic polyfills are injected (explicit modules overrides still apply).
proposalsbooleanfalseInclude shipped ES proposals (esnext.*) and enable es.* to esnext.* version fallback in "usage-global" mode.
modulesRecord<string, boolean>{}Per-module overrides: true force-includes a core-js module and false excludes it. Unknown module names return an error diagnostic.
import { transformSync } from "@swc-next/core";

const output = transformSync("Object.fromEntries([]);", {
  transformer: {
    target: { chrome: "71" },
    polyfill: {
      mode: "usage-global",
      coreJs: "3.38",
    },
  },
});

To lower syntax with an ES edition while selecting polyfills by browser versions, specify polyfill.target separately:

import { transformSync } from "@swc-next/core";

const output = transformSync("const x = a ?? Object.fromEntries([]);", {
  transformer: {
    target: "es2019",
    polyfill: {
      mode: "usage-global",
      coreJs: "3.38",
      target: ["chrome >= 71"],
      modules: { "es.array.at": true },
    },
  },
});

JsOutput

interface SourceMap {
  version: number;
  sources: string[];
  sourcesContent: string[];
  names: string[];
  mappings: string;
}

interface JsOutput {
  code: string;
  map?: SourceMap;
  diagnostics: Diagnostic[];
}
FieldContents
codeTransformed JavaScript (or TypeScript/JSX when preserved). Empty string when parsing, semantic checks, or transformer configuration reports an error diagnostic.
mapSource Map v3 object when sourceMap is true; absent otherwise.
diagnosticsSyntax, semantic (when parser.semanticErrors is enabled), configuration, and transform diagnostics.

See Diagnostics and positions for the Diagnostic and DiagnosticLabel shapes.