CtrlK
BlogDocsLog inGet started
Tessl Logo

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.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

core-transformation.mddocs/

Core Transformation

The core transformation pipeline handles JavaScript, TypeScript, JSX, JSON, and asset file processing through Metro's comprehensive Babel-based transformation system.

Capabilities

Transform Function

Main transformation function that processes files through Metro's complete pipeline including parsing, Babel transformation, dependency collection, module wrapping, optimization, and source map generation.

/**
 * Transform files through Metro's complete transformation pipeline
 * @param config - Transformer configuration object containing Babel, minifier, and asset settings
 * @param projectRoot - Absolute path to project root directory
 * @param filename - Relative path to file being transformed (used for source maps and error reporting)
 * @param data - File content as Buffer
 * @param options - Transformation options including dev mode, platform, and optimization settings
 * @returns Promise resolving to transformation result with dependencies and output
 */
function transform(
  config: JsTransformerConfig,
  projectRoot: string,
  filename: string,
  data: Buffer,
  options: JsTransformOptions
): Promise<TransformResponse>;

Usage Examples:

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

// Transform a React Native component
const config = {
  babelTransformerPath: require.resolve("@react-native/metro-babel-transformer"),
  minifierPath: require.resolve("metro-minify-terser"),
  assetRegistryPath: "react-native/Libraries/Image/AssetRegistry",
  assetPlugins: [],
  enableBabelRCLookup: true,
  enableBabelRuntime: false,
  globalPrefix: "",
  hermesParser: false,
  minifierConfig: {},
  optimizationSizeLimit: 150000,
  publicPath: "/assets",
  allowOptionalDependencies: "ignore",
  unstable_disableModuleWrapping: false,
  unstable_compactOutput: false,
  unstable_allowRequireContext: false,
};

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

// Transform JavaScript/JSX file
const jsFile = fs.readFileSync("./src/components/Button.js");
const jsResult = await transform(
  config,
  process.cwd(),
  "./src/components/Button.js",
  jsFile,
  options
);

console.log(jsResult.output[0].data.code); // Transformed code
console.log(jsResult.dependencies); // Array of module dependencies

// Transform JSON file
const jsonFile = fs.readFileSync("./data/config.json");
const jsonResult = await transform(
  config,
  process.cwd(),
  "./data/config.json",
  jsonFile,
  { ...options, type: "module" }
);

// Transform asset file
const imageFile = fs.readFileSync("./assets/logo.png");
const assetResult = await transform(
  config,
  process.cwd(),
  "./assets/logo.png",
  imageFile,
  { ...options, type: "asset" }
);

Transformation Pipeline Stages

The transformation process includes several key stages:

1. File Type Detection and Parsing

  • JavaScript/JSX/TypeScript: Parsed using Babylon parser with AST generation
  • JSON: Direct content processing and CommonJS wrapping
  • Assets: Metadata extraction and asset registry integration

2. Babel Transformation

  • Plugin-based transformations through configured Babel transformer
  • Import/export handling with optional experimental import support
  • Platform-specific code inlining and optimization

3. Dependency Collection

  • Module dependency analysis and extraction
  • Dynamic require handling with configurable behavior
  • Import/export statement processing

4. Module Wrapping

  • CommonJS module wrapping with dependency injection
  • Script vs module handling for different execution contexts
  • Global prefix application and scoping

5. Optimization

  • Constant folding in production builds
  • Inline require transformations for performance
  • Pseudo-global normalization for minification

6. Source Map Generation

  • Comprehensive source map creation throughout pipeline
  • Function map generation for debugging
  • Segment-based mapping for efficient storage

File Type Processing

JavaScript/JSX/TypeScript Files

Processed through the complete Babel transformation pipeline with full AST manipulation, dependency analysis, and optimization.

// Input file type for JS/JSX/TS processing
interface JSFile {
  filename: string;
  inputFileSize: number;
  code: string;
  type: JSFileType;
  ast?: BabelNodeFile;
  functionMap: FBSourceFunctionMap | null;
  unstable_importDeclarationLocs?: Set<string>;
}

Processing steps:

  1. AST parsing with Babylon
  2. "use strict" directive injection for modules
  3. Babel plugin transformations (import/export, inline requires, platform inlining)
  4. Constant folding optimization (production only)
  5. Dependency collection and analysis
  6. Module wrapping or script handling
  7. Code generation with source maps
  8. Optional minification

JSON Files

JSON files are converted to CommonJS modules for seamless integration with JavaScript bundling.

// Input file type for JSON processing
interface JSONFile {
  filename: string;
  inputFileSize: number;
  code: string;
  type: Type;
}

Processing steps:

  1. JSON content validation
  2. CommonJS module wrapper generation
  3. Optional minification
  4. Source map generation

Asset Files

Asset files (images, fonts, etc.) are converted to JavaScript modules that reference asset registry entries.

// Input file type for asset processing
interface AssetFile {
  filename: string;
  inputFileSize: number;
  code: string;
  type: "asset";
}

Processing steps:

  1. Asset metadata extraction (dimensions, file size, etc.)
  2. Asset registry integration
  3. JavaScript module AST generation
  4. Standard JavaScript processing pipeline

Transformation Response

interface TransformResponse {
  /** Array of module dependencies discovered during transformation */
  dependencies: TransformResultDependency[];
  /** Array of output chunks (JavaScript or Hermes bytecode) */
  output: (JsOutput | BytecodeOutput)[];
}

interface JsOutput {
  data: {
    /** Transformed JavaScript code ready for bundling */
    code: string;
    /** Number of lines in the transformed code */
    lineCount: number;
    /** Source map segments for debugging */
    map: MetroSourceMapSegmentTuple[];
    /** Function map for advanced debugging (React Native) */
    functionMap: FBSourceFunctionMap | null;
  };
  /** File type classification for bundler handling */
  type: JSFileType;
}

interface BytecodeOutput {
  /** Opaque bytecode data for Hermes runtime */
  data: unknown;
  /** Bytecode file type classification */
  type: BytecodeFileType;
}

Error Handling

The transformation pipeline provides detailed error reporting with file context:

class InvalidRequireCallError extends Error {
  /** Original error from dependency collection */
  innerError: InternalInvalidRequireCallError;
  /** File where the error occurred */
  filename: string;
  
  constructor(innerError: InternalInvalidRequireCallError, filename: string);
}

Common error scenarios:

  • Invalid require() call syntax
  • Malformed import/export statements
  • Babel transformation failures
  • Minification syntax errors
  • Reserved string conflicts (e.g., Metro internal variables)

Error context includes:

  • File path and line numbers
  • Specific syntax issues
  • Configuration that led to the error
  • Suggestions for resolution

docs

cache-management.md

configuration.md

core-transformation.md

error-handling.md

index.md

tile.json