or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cache-management.mdconfiguration.mdcore-transformation.mderror-handling.mdindex.md
tile.json

tessl/npm-metro-transform-worker

Transform worker for Metro bundler that handles JavaScript, TypeScript, JSX, JSON, and asset transformations through a comprehensive Babel-based pipeline.

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

To install, run

npx @tessl/cli install tessl/npm-metro-transform-worker@0.83.0

index.mddocs/

Metro Transform Worker

Metro Transform Worker is the core transformation engine for Meta's Metro JavaScript bundler. It handles the conversion of JavaScript, TypeScript, JSX, JSON, and asset files through a comprehensive Babel-based pipeline, providing dependency analysis, code optimization, minification, and source map generation for React Native and web applications.

Package Information

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

Core Imports

const { transform, getCacheKey } = require("metro-transform-worker");

For ESM:

import { transform, getCacheKey } from "metro-transform-worker";

Basic Usage

const { transform } = require("metro-transform-worker");
const fs = require("fs");

// Basic file transformation
const config = {
  babelTransformerPath: require.resolve("@react-native/metro-babel-transformer"),
  minifierPath: require.resolve("metro-minify-terser"),
  assetRegistryPath: "react-native/Libraries/Image/AssetRegistry",
  assetPlugins: [],
  // ... other configuration options
};

const options = {
  dev: true,
  hot: false,
  inlinePlatform: false,
  inlineRequires: false,
  minify: false,
  platform: "ios",
  type: "module",
  unstable_transformProfile: "default",
};

// Transform a JavaScript file
const fileData = fs.readFileSync("./src/MyComponent.js");
const result = await transform(
  config,
  "/path/to/project/root",
  "./src/MyComponent.js",
  fileData,
  options
);

console.log(result.output[0].data.code); // Transformed code
console.log(result.dependencies); // Module dependencies

Architecture

Metro Transform Worker is built around several key components:

  • Transformation Pipeline: Multi-stage processing including parsing, Babel transformation, dependency collection, and optimization
  • File Type Handlers: Specialized processing for JavaScript, TypeScript, JSX, JSON, and asset files with optional Hermes bytecode output
  • Plugin System: Extensible Babel plugin integration with Metro-specific transform plugins
  • Caching System: Cache key generation for efficient incremental builds
  • Source Maps: Comprehensive source map generation and handling throughout the pipeline
  • Error Handling: Detailed error reporting with file context and debugging information

Capabilities

Core Transformation

Primary transformation function that processes files through the complete Metro pipeline, handling JavaScript/TypeScript/JSX transformations, dependency analysis, and code optimization.

/**
 * Transform files through Metro's complete transformation pipeline
 * @param config - Transformer configuration object
 * @param projectRoot - Absolute path to project root directory
 * @param filename - Relative path to file being transformed
 * @param data - File content as Buffer
 * @param options - Transformation options
 * @returns Promise resolving to transformation result with dependencies and output
 */
function transform(
  config: JsTransformerConfig,
  projectRoot: string,
  filename: string,
  data: Buffer,
  options: JsTransformOptions
): Promise<TransformResponse>;

interface TransformResponse {
  dependencies: TransformResultDependency[];
  output: (JsOutput | BytecodeOutput)[];
}

interface JsOutput {
  data: {
    code: string;
    lineCount: number;
    map: MetroSourceMapSegmentTuple[];
    functionMap: FBSourceFunctionMap | null;
  };
  type: JSFileType;
}

Core Transformation

Cache Management

Cache key generation for efficient incremental builds and cache invalidation.

/**
 * Generate cache key for transformer configuration
 * @param config - Transformer configuration object
 * @returns String cache key based on configuration and dependencies
 */
function getCacheKey(config: JsTransformerConfig): string;

Cache Management

Configuration System

Comprehensive configuration system for customizing transformation behavior, Babel integration, and optimization settings.

interface JsTransformerConfig {
  assetPlugins: ReadonlyArray<string>;
  assetRegistryPath: string;
  asyncRequireModulePath: string;
  babelTransformerPath: string;
  dynamicDepsInPackages: DynamicRequiresBehavior;
  enableBabelRCLookup: boolean;
  enableBabelRuntime: boolean | string;
  globalPrefix: string;
  hermesParser: boolean;
  minifierConfig: MinifierConfig;
  minifierPath: string;
  optimizationSizeLimit: number;
  publicPath: string;
  allowOptionalDependencies: AllowOptionalDependencies;
  unstable_collectDependenciesPath: string;
  unstable_dependencyMapReservedName?: string;
  unstable_disableModuleWrapping: boolean;
  unstable_disableNormalizePseudoGlobals: boolean;
  unstable_compactOutput: boolean;
  unstable_allowRequireContext: boolean;
  unstable_memoizeInlineRequires?: boolean;
  unstable_nonMemoizedInlineRequires?: ReadonlyArray<string>;
  unstable_renameRequire?: boolean;
}

interface JsTransformOptions {
  customTransformOptions?: CustomTransformOptions;
  dev: boolean;
  experimentalImportSupport?: boolean;
  hot: boolean;
  inlinePlatform: boolean;
  inlineRequires: boolean;
  minify: boolean;
  nonInlinedRequires?: ReadonlyArray<string>;
  platform?: string;
  runtimeBytecodeVersion?: number;
  type: Type;
  unstable_disableES6Transforms?: boolean;
  unstable_memoizeInlineRequires?: boolean;
  unstable_nonMemoizedInlineRequires?: ReadonlyArray<string>;
  unstable_staticHermesOptimizedRequire?: boolean;
  unstable_transformProfile: TransformProfile;
}

Configuration System

Error Handling

Detailed error handling with context and debugging information for transformation failures.

class InvalidRequireCallError extends Error {
  innerError: InternalInvalidRequireCallError;
  filename: string;
  
  constructor(innerError: InternalInvalidRequireCallError, filename: string);
}

Error Handling

Types

Core Types

type Type = "script" | "module" | "asset";
type JSFileType = "js/script" | "js/module" | "js/module/asset";
type BytecodeFileType = "bytecode/module" | "bytecode/module/asset" | "bytecode/script";
type DynamicRequiresBehavior = "reject" | "throwAtRuntime";

interface MinifierOptions {
  code: string;
  map?: BasicSourceMap;
  filename: string;
  reserved: ReadonlyArray<string>;
  config: MinifierConfig;
}

interface MinifierResult {
  code: string;
  map?: BasicSourceMap;
}

type Minifier = (options: MinifierOptions) => MinifierResult | Promise<MinifierResult>;

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

Metro Integration Types

interface TransformResultDependency {
  name: string;
  type: string;
  // Additional Metro-specific dependency metadata
}

type MetroSourceMapSegmentTuple = [number, number, number?, number?, string?];

interface FBSourceFunctionMap {
  names: ReadonlyArray<string>;
  mappings: string;
}

interface BytecodeOutput {
  data: unknown;
  type: BytecodeFileType;
}