WebAssembly module for SWC compiler providing JavaScript/TypeScript parsing, transformation, and minification in browsers and Node.js
—
Transform JavaScript and TypeScript code with configurable compilation targets, module systems, and optimization settings. Supports both string input and AST Program objects.
Transforms source code or AST asynchronously with comprehensive configuration options.
/**
* Transform source code or AST asynchronously
* @param code - Source code string or Program AST
* @param options - Transformation configuration options
* @param experimental_plugin_bytes_resolver - Plugin bytes resolver (experimental)
* @returns Promise resolving to transformation output
*/
function transform(
code: string | Program,
options?: Options,
experimental_plugin_bytes_resolver?: any
): Promise<Output>;Usage Examples:
import * as swc from "@swc/wasm";
// Transform TypeScript to JavaScript
const result = await swc.transform(`
interface Config {
port: number;
host: string;
}
const config: Config = {
port: 3000,
host: "localhost"
};
export default config;
`, {
jsc: {
target: "es2018",
parser: {
syntax: "typescript"
}
},
module: {
type: "commonjs"
}
});
console.log(result.code);
// Output: CommonJS JavaScript code
// Transform with React JSX
const jsxResult = await swc.transform(`
function App() {
return <div>Hello World</div>;
}
`, {
jsc: {
target: "es2015",
parser: {
syntax: "ecmascript",
jsx: true
},
transform: {
react: {
pragma: "React.createElement",
pragmaFrag: "React.Fragment"
}
}
}
});
// Transform with source maps
const mappedResult = await swc.transform(sourceCode, {
sourceMaps: true,
filename: "input.ts",
jsc: {
target: "es2020",
parser: {
syntax: "typescript"
}
}
});
console.log(mappedResult.map); // Source map stringTransforms source code or AST synchronously with identical interface to async version.
/**
* Transform source code or AST synchronously
* @param code - Source code string or Program AST
* @param opts - Transformation configuration options
* @param experimental_plugin_bytes_resolver - Plugin bytes resolver (experimental)
* @returns Transformation output
*/
function transformSync(
code: string | Program,
opts?: Options,
experimental_plugin_bytes_resolver?: any
): Output;Usage Examples:
import * as swc from "@swc/wasm";
// Synchronous transformation
const result = swc.transformSync(`class Example {}`, {
jsc: {
target: "es5",
parser: {
syntax: "ecmascript"
}
}
});
// Transform AST object
const ast = swc.parseSync(`const x = 1;`, {
syntax: "ecmascript"
});
const transformed = swc.transformSync(ast, {
jsc: {
target: "es3"
}
});interface Options extends Config {
/** Parse as script instead of module */
script?: boolean;
/** Working directory for path resolution */
cwd?: string;
/** Caller identification options */
caller?: CallerOptions;
/** Filename for error reporting and config resolution */
filename?: string;
/** Root directory for config resolution */
root?: string;
/** Root resolution mode */
rootMode?: "root" | "upward" | "upward-optional";
/** Environment name for config selection */
envName?: string;
/** Config file path or disable */
configFile?: string | boolean;
/** Enable .swcrc file loading */
swcrc?: boolean;
/** Root packages for .swcrc resolution */
swcrcRoots?: boolean | MatchPattern | MatchPattern[];
/** Input source map */
inputSourceMap?: boolean | string;
/** Source filename in source maps */
sourceFileName?: string;
/** Source root in source maps */
sourceRoot?: string;
/** Plugin configuration */
plugin?: Plugin;
/** Module type detection */
isModule?: boolean | "unknown" | "commonjs";
/** Output path for source map fixing */
outputPath?: string;
}
interface CallerOptions {
name: string;
[key: string]: any;
}interface Config {
/** File matching patterns */
test?: string | string[];
/** File exclusion patterns */
exclude?: string | string[];
/** Environment-based configuration */
env?: EnvConfig;
/** JavaScript compiler configuration */
jsc?: JscConfig;
/** Module transformation configuration */
module?: ModuleConfig;
/** Enable minification */
minify?: boolean;
/** Source map generation */
sourceMaps?: boolean | "inline";
/** Include source content in source maps */
inlineSourcesContent?: boolean;
}interface JscConfig {
/** Use loose transformations */
loose?: boolean;
/** Parser configuration */
parser?: ParserConfig;
/** Transformation settings */
transform?: TransformConfig;
/** Use external helpers from @swc/helpers */
externalHelpers?: boolean;
/** Compilation target */
target?: JscTarget;
/** Keep class names during minification */
keepClassNames?: boolean;
/** Experimental features */
experimental?: {
optimizeHygiene?: boolean;
keepImportAssertions?: boolean;
cacheRoot?: string;
plugins?: Array<[string, Record<string, any>]>;
};
/** Base URL for path resolution */
baseUrl?: string;
/** Path mapping */
paths?: { [from: string]: string[] };
/** Minification options */
minify?: JsMinifyOptions;
/** Preserve all comments */
preserveAllComments?: boolean;
/** Output settings */
output?: {
charset?: "utf8" | "ascii";
};
}
type JscTarget = "es3" | "es5" | "es2015" | "es2016" | "es2017" | "es2018" | "es2019" | "es2020" | "es2021" | "es2022";interface TransformConfig {
/** React transformation settings */
react?: ReactConfig;
/** Constant modules configuration */
constModules?: ConstModulesConfig;
/** Optimizer configuration */
optimizer?: OptimizerConfig;
/** Legacy decorator support */
legacyDecorator?: boolean;
/** Decorator metadata support */
decoratorMetadata?: boolean;
/** Treat const enum as enum */
treatConstEnumAsEnum?: boolean;
/** Use define for class fields */
useDefineForClassFields?: boolean;
}
interface ReactConfig {
/** JSX pragma function */
pragma?: string;
/** JSX Fragment component */
pragmaFrag?: string;
/** Throw on XML namespaced tags */
throwIfNamespace?: boolean;
/** Development mode helpers */
development?: boolean;
/** Use Object.assign instead of _extends */
useBuiltins?: boolean;
/** Fast refresh configuration */
refresh?: boolean | {
refreshReg?: string;
refreshSig?: string;
emitFullSignatures?: boolean;
};
/** JSX runtime mode */
runtime?: "automatic" | "classic";
/** JSX import source */
importSource?: string;
}type ModuleConfig = Es6Config | CommonJsConfig | UmdConfig | AmdConfig | NodeNextConfig | SystemjsConfig;
interface BaseModuleConfig {
/** Strict mode for __esModule */
strict?: boolean;
/** Emit 'use strict' directive */
strictMode?: boolean;
/** Lazy import initialization */
lazy?: boolean | string[];
/** Import interop strategy */
importInterop?: "swc" | "babel" | "node" | "none";
/** Output file extension */
outFileExtension?: "js" | "mjs" | "cjs";
/** Export interop annotation */
exportInteropAnnotation?: boolean;
/** Preserve dynamic imports */
ignoreDynamic?: boolean;
/** Allow top-level this */
allowTopLevelThis?: boolean;
/** Preserve import.meta */
preserveImportMeta?: boolean;
/** Resolve fully */
resolveFully?: boolean;
}
interface Es6Config extends BaseModuleConfig {
type: "es6";
}
interface CommonJsConfig extends BaseModuleConfig {
type: "commonjs";
}
interface UmdConfig extends BaseModuleConfig {
type: "umd";
globals?: { [key: string]: string };
}
interface AmdConfig extends BaseModuleConfig {
type: "amd";
moduleId?: string;
}
interface NodeNextConfig extends BaseModuleConfig {
type: "nodenext";
}
interface SystemjsConfig {
type: "systemjs";
allowTopLevelThis?: boolean;
}interface Output {
/** Transformed code */
code: string;
/** Source map (if enabled) */
map?: string;
/** Diagnostic messages */
diagnostics: string[];
}Usage Example:
const result = await swc.transform(code, options);
console.log(result.code); // Transformed JavaScript
console.log(result.map); // Source map (if sourceMaps: true)
console.log(result.diagnostics); // Array of warning/error messagesconst result = await swc.transform(`
import { utils } from '@app/utils';
import { config } from '@shared/config';
`, {
filename: "src/main.ts",
jsc: {
parser: { syntax: "typescript" },
target: "es2018",
baseUrl: "./",
paths: {
"@app/*": ["src/*"],
"@shared/*": ["shared/*"]
}
},
module: { type: "commonjs" }
});const result = await swc.transform(code, {
env: {
targets: {
"chrome": "58",
"ie": "11"
},
mode: "usage",
coreJs: "3.21"
},
jsc: {
parser: { syntax: "typescript" },
target: "es5"
}
});Install with Tessl CLI
npx tessl i tessl/npm-swc--wasm