Base Babel transformer for Metro bundler providing JavaScript/TypeScript code transformation with dual parser support
npx @tessl/cli install tessl/npm-metro-babel-transformer@0.83.0Metro Babel Transformer is the base Babel transformation engine for Metro bundler, providing JavaScript and TypeScript code transformation capabilities. It supports dual parser modes (Babel or Hermes), configurable transformation options, and generates AST output with metadata for Metro's bundling pipeline.
npm install metro-babel-transformerconst { transform } = require("metro-babel-transformer");For TypeScript users:
import { transform, BabelTransformerArgs, BabelTransformerOptions } from "metro-babel-transformer";
import type { File as BabelNodeFile } from "@babel/types";const { transform } = require("metro-babel-transformer");
// Transform JavaScript source code
const result = transform({
filename: "example.js",
src: `
const greeting = (name) => {
return \`Hello, \${name}!\`;
};
export default greeting;
`,
options: {
dev: true,
enableBabelRuntime: false,
enableBabelRCLookup: false,
globalPrefix: "__metro__",
hot: false,
inlineRequires: undefined, // Reserved for future use
minify: false,
platform: null,
publicPath: "/assets",
projectRoot: "/path/to/project",
},
plugins: [
// Optional Babel plugins array
["@babel/plugin-transform-modules-commonjs", {}],
],
});
console.log("Transformed AST:", result.ast);
console.log("Metadata:", result.metadata);Metro Babel Transformer is designed around several key concepts:
Transforms JavaScript and TypeScript source code using Babel with configurable options and plugins.
/**
* Transform source code using Babel with configurable options
* @param args - Transformation arguments containing source, options, and plugins
* @returns Object with transformed AST and metadata
*/
function transform(args: BabelTransformerArgs): {
ast: BabelNodeFile;
functionMap?: BabelFileFunctionMapMetadata; // Deprecated - will be removed in future release. Function maps are now generated by Babel plugins and included in metadata.
metadata?: MetroBabelFileMetadata;
};interface BabelTransformerArgs {
/** Path to the source file being transformed */
readonly filename: string;
/** Transformer configuration options */
readonly options: BabelTransformerOptions;
/** Optional array of Babel plugins to apply */
readonly plugins?: Array<string | [string, any] | BabelPluginInstance>;
/** Source code string to transform */
readonly src: string;
}interface BabelTransformerOptions {
/** Custom transform options passed to plugins */
readonly customTransformOptions?: CustomTransformOptions;
/** Development mode flag - affects BABEL_ENV and optimizations */
readonly dev: boolean;
/** Enable lookup of .babelrc files */
readonly enableBabelRCLookup?: boolean;
/** Enable Babel runtime helpers (boolean or specific runtime package) */
readonly enableBabelRuntime: boolean | string;
/** Path to babel config file to extend */
readonly extendsBabelConfigPath?: string;
/** Enable experimental import statement support */
readonly experimentalImportSupport?: boolean;
/** Use Hermes parser instead of Babel parser */
readonly hermesParser?: boolean;
/** Hot reload mode flag */
readonly hot: boolean;
/** Inline requires setting (reserved for future use) */
readonly inlineRequires?: void;
/** Minification flag */
readonly minify: boolean;
/** Disable ES6 transforms (experimental) */
readonly unstable_disableES6Transforms?: boolean;
/** Target platform (e.g., 'ios', 'android', 'web') */
readonly platform: string | null;
/** Project root directory path */
readonly projectRoot: string;
/** Public path for assets */
readonly publicPath: string;
/** Transform profile for different optimization levels */
readonly unstable_transformProfile?: TransformProfile;
/** Global prefix for generated identifiers */
readonly globalPrefix: string;
}type TransformProfile = 'default' | 'hermes-stable' | 'hermes-canary';interface CustomTransformOptions {
[key: string]: unknown;
}Complete interface for implementing custom transformers compatible with Metro.
interface BabelTransformer {
/** Main transform function */
transform: (args: BabelTransformerArgs) => {
ast: BabelNodeFile;
functionMap?: BabelFileFunctionMapMetadata; // Deprecated - will be removed in future release. Function maps are now generated by Babel plugins and included in metadata.
metadata?: MetroBabelFileMetadata;
};
/** Optional cache key generator for caching transformed results */
getCacheKey?: () => string;
}These types are imported from @babel/core:
/** Babel AST node representing a complete file */
type BabelNodeFile = import('@babel/types').File;
/** Base Babel file metadata */
interface BabelFileMetadata {
[key: string]: any;
}
/** Babel core configuration options */
interface BabelCoreOptions {
plugins?: Array<string | [string, any] | BabelPluginInstance>;
[key: string]: any;
}
/** Babel plugin instance */
interface BabelPluginInstance {
(babel: any, options?: any): {
visitor: any;
[key: string]: any;
};
}interface MetroBabelFileMetadata extends BabelFileMetadata {
/** Metro-specific metadata extensions */
metro?: {
/** Function mapping data for debugging */
functionMap?: BabelFileFunctionMapMetadata;
/** Import declaration locations for optimization */
unstable_importDeclarationLocs?: BabelFileImportLocsMetadata;
};
}
interface BabelFileFunctionMapMetadata {
/** Array of function names in the source */
readonly names: ReadonlyArray<string>;
/** Source map style mappings for function locations */
readonly mappings: string;
}
type BabelFileImportLocsMetadata = ReadonlySet<string>;const { transform } = require("metro-babel-transformer");
const result = transform({
filename: "app.js",
src: "const app = () => 'Hello World';",
options: {
dev: false,
enableBabelRuntime: false,
enableBabelRCLookup: true,
globalPrefix: "__app__",
hot: false,
minify: true,
platform: "web",
publicPath: "/static",
projectRoot: process.cwd(),
},
});const result = transform({
filename: "component.js",
src: "export const Component = () => <div>React Component</div>;",
options: {
dev: true,
enableBabelRuntime: "@babel/runtime",
hermesParser: true, // Use Hermes parser instead of Babel
hot: true,
minify: false,
platform: "ios",
projectRoot: "/Users/dev/my-app",
publicPath: "/",
globalPrefix: "__metro__",
},
plugins: [
["@babel/plugin-transform-react-jsx", { runtime: "automatic" }],
],
});const result = transform({
filename: "feature.ts",
src: "const feature: Feature = { enabled: true };",
options: {
dev: true,
enableBabelRuntime: false,
hot: false,
minify: false,
platform: "android",
projectRoot: "/project",
publicPath: "/assets",
globalPrefix: "__app__",
customTransformOptions: {
experimentalDecorators: true,
strictMode: false,
},
unstable_transformProfile: "hermes-stable",
},
});The transform function may throw errors in the following scenarios:
Always wrap transform calls in try-catch blocks for production usage:
try {
const result = transform(transformArgs);
// Process result
} catch (error) {
console.error("Transform failed:", error.message);
// Handle transformation error
}