or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-metro-babel-transformer

Base Babel transformer for Metro bundler providing JavaScript/TypeScript code transformation with dual parser support

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/metro-babel-transformer@0.83.x

To install, run

npx @tessl/cli install tessl/npm-metro-babel-transformer@0.83.0

index.mddocs/

Metro Babel Transformer

Metro 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.

Package Information

  • Package Name: metro-babel-transformer
  • Package Type: npm
  • Language: JavaScript (with Flow types)
  • Installation: npm install metro-babel-transformer

Core Imports

const { transform } = require("metro-babel-transformer");

For TypeScript users:

import { transform, BabelTransformerArgs, BabelTransformerOptions } from "metro-babel-transformer";
import type { File as BabelNodeFile } from "@babel/types";

Basic Usage

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);

Architecture

Metro Babel Transformer is designed around several key concepts:

  • Transform Function: Core transformation engine that processes source code through Babel
  • Dual Parser Support: Can use either Babel's parser or Hermes parser for JavaScript parsing
  • Environment Management: Automatically configures BABEL_ENV based on development/production mode
  • AST Processing: Returns transformed Abstract Syntax Tree ready for Metro's bundling pipeline
  • Metadata Generation: Provides transformation metadata for debugging and optimization

Capabilities

Code Transformation

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;
};

Transformer Arguments

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;
}

Transformer Options

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;
}

Transform Profiles

type TransformProfile = 'default' | 'hermes-stable' | 'hermes-canary';

Custom Transform Options

interface CustomTransformOptions {
  [key: string]: unknown;
}

Babel Transformer Interface

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;
}

External Types

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;
  };
}

Metadata Types

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>;

Usage Examples

Basic Transformation

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(),
  },
});

Hermes Parser Usage

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" }],
  ],
});

With Custom Transform Options

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",
  },
});

Error Handling

The transform function may throw errors in the following scenarios:

  • Syntax Errors: When source code contains invalid JavaScript/TypeScript syntax
  • Plugin Errors: When specified Babel plugins encounter configuration or processing errors
  • Parser Errors: When the selected parser (Babel or Hermes) fails to parse the source
  • File System Errors: When babel config files specified in options cannot be read

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
}