or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

ast-types.mdbrowser.mdcli.mdindex.mdmodules.mdregistration.mdtransformation.mdtransformers.md
tile.json

transformation.mddocs/

Core Transformation API

The core transformation functionality for converting ES6+ code to ES5. This is the primary API for programmatic usage of 6to5.

Transform Functions

Basic Transformation

/**
 * Transform ES6+ code to ES5 with comprehensive options
 * @param code - Source code string to transform
 * @param opts - Transformation options object
 * @returns Transform result with code, map, and ast
 */
function transform(code: string, opts?: TransformOptions): TransformResult;

AST-Based Transformation

/**
 * Transform from existing parsed AST
 * @param ast - Pre-parsed Abstract Syntax Tree
 * @param code - Original source code string for source maps
 * @param opts - Transformation options
 * @returns Transform result with generated code
 */
function fromAst(ast: Node, code: string, opts?: TransformOptions): TransformResult;

File Operations

/**
 * Transform file asynchronously
 * @param filename - Path to input file
 * @param opts - Transformation options
 * @param callback - Completion callback
 */
function transformFile(filename: string, opts: TransformOptions, callback: (err: Error | null, result?: TransformResult) => void): void;

/**
 * Transform file asynchronously with default options
 * @param filename - Path to input file  
 * @param callback - Completion callback
 */
function transformFile(filename: string, callback: (err: Error | null, result?: TransformResult) => void): void;

/**
 * Transform file synchronously
 * @param filename - Path to input file
 * @param opts - Transformation options
 * @returns Transform result
 */
function transformFileSync(filename: string, opts?: TransformOptions): TransformResult;

Data Types

Transform Result

interface TransformResult {
  /**
   * Generated ES5 code
   */
  code: string;
  
  /**
   * Source map object (if sourceMap option enabled)
   */
  map?: SourceMap;
  
  /**
   * Transformed AST (if ast option is true)
   */
  ast?: Node;
}

Transform Options

interface TransformOptions {
  /**
   * Input filename for source maps and error reporting
   */
  filename?: string;
  
  /**
   * Relative filename for source maps
   */
  filenameRelative?: string;
  
  /**
   * Module output format
   * @default "common"
   */
  modules?: "common" | "amd" | "umd" | "system" | "ignore";
  
  /** 
   * Source map generation
   * - true: External source map
   * - "inline": Inline source map comment
   * - false: No source map  
   * @default false
   */
  sourceMap?: boolean | "inline";
  
  /**
   * Source map filename
   */
  sourceMapName?: string;
  
  /**
   * Original source filename in source map
   */
  sourceFileName?: string;
  
  /**
   * Source root path for source map
   */
  sourceRoot?: string;
  
  /**
   * Module root path for relative imports
   */
  moduleRoot?: string;
  
  /**
   * Array of transformer names to ONLY use (whitelist)
   */
  whitelist?: string[];
  
  /**
   * Array of transformer names to NOT use (blacklist)
   */
  blacklist?: string[];
  
  /**
   * Array of optional transformers to enable
   */
  optional?: string[];
  
  /**
   * Array of transformers to enable loose mode on
   */
  loose?: string[];
  
  /**
   * Enable experimental ES7 features
   * @default false
   */
  experimental?: boolean;
  
  /**
   * Enable playground features
   * @default false
   */
  playground?: boolean;
  
  /**
   * Use runtime helpers instead of inline helpers
   * @default false
   */
  runtime?: boolean;
  
  /**
   * Preserve comments in output
   * @default true
   */
  comments?: boolean;
  
  /**
   * Compact output (minimal whitespace)
   * @default false
   */
  compact?: boolean;
  
  /**
   * Include generated code in result
   * @default true
   */
  code?: boolean;
  
  /**
   * Include AST in result
   * @default true
   */
  ast?: boolean;
  
  /**
   * Comment to prepend to auxiliary code
   */
  auxiliaryComment?: string;
  
  /**
   * React compatibility mode for pre-v0.12
   * @default false
   */
  reactCompat?: boolean;
  
  /**
   * Insert module IDs in modules
   * @default false
   */
  moduleIds?: boolean;
  
  /**
   * Keep file extensions when generating module IDs
   * @default false
   */
  keepModuleIdExtensions?: boolean;
}

Usage Examples

Basic Code Transformation

const to5 = require("6to5");

// Transform arrow function
const result = to5.transform("const add = (a, b) => a + b;");
console.log(result.code);
// "use strict";
// var add = function add(a, b) {
//   return a + b;
// };

// Transform class with options
const classResult = to5.transform(`
class Calculator {
  add(a, b) {
    return a + b;
  }
}
`, {
  loose: ["es6.classes"],
  comments: false
});

File Transformation

// Synchronous file transformation
const fileResult = to5.transformFileSync("input.js", {
  modules: "amd",
  sourceMap: true,
  optional: ["es7.comprehensions"]
});

// Asynchronous file transformation
to5.transformFile("input.js", {
  modules: "umd",
  runtime: true
}, (err, result) => {
  if (err) throw err;
  console.log(result.code);
});

Advanced Configuration

// Transform with comprehensive options
const advancedResult = to5.transform(sourceCode, {
  filename: "app.js",
  modules: "common", 
  sourceMap: "inline",
  optional: [
    "es7.comprehensions",
    "es7.objectRestSpread",
    "es7.exponentiationOperator"
  ],
  loose: [
    "es6.classes",
    "es6.modules"
  ],
  blacklist: [
    "es6.forOf"  // Don't transform for-of loops
  ],
  runtime: true,
  auxiliaryComment: "Generated by 6to5",
  experimental: true
});

AST-Based Transformation

const acorn = require("acorn-6to5");

// Parse code to AST first
const ast = acorn.parse("class Foo {}", {
  ecmaVersion: 6,
  sourceType: "module"
});

// Transform from AST
const result = to5.fromAst(ast, "class Foo {}", {
  modules: "common"
});

Transformer Management

/**
 * Validate and normalize transformer names
 * @param type - Context type ("blacklist", "whitelist", etc.)
 * @param rawKeys - Array of transformer names
 * @returns Normalized transformer names
 */
function _ensureTransformerNames(type: string, rawKeys: string[]): string[];

/**
 * Available transformers by name
 */
const transformers: { [key: string]: Transformer };

/**
 * Transformer namespaces (es6, es7, etc.)
 */
const namespaces: { [namespace: string]: string[] };

/**
 * Transformer namespace mappings
 */
const transformerNamespaces: { [transformer: string]: string };

/**
 * Module formatters for different output types
 */
const moduleFormatters: { [format: string]: ModuleFormatter };

/**
 * Deprecated transformer name mappings
 */
const deprecatedTransformerMap: { [oldName: string]: string };

Error Handling

The transformation functions throw errors for various conditions:

  • SyntaxError: Invalid input JavaScript syntax
  • ReferenceError: Unknown transformer names with format "Unknown transformer {name} specified in {type}"
  • TypeError: Invalid option types
  • Error: File system errors for file operations

Deprecation Warnings

6to5 logs deprecation warnings to console.error for renamed transformers:

// Example deprecation warning
console.error(
  "The transformer oldName has been renamed to newName in v3.0.0 - " +
  "backwards compatibility will be removed 4.0.0"
);

Error Examples

try {
  const result = to5.transform(invalidCode);
} catch (err) {
  if (err instanceof SyntaxError) {
    console.error("Syntax error:", err.message);
  } else if (err instanceof ReferenceError) {
    console.error("Unknown transformer:", err.message);
    // Format: "Unknown transformer foo specified in blacklist - transformer key names..."
  }
}

// Handle deprecated transformer usage
try {
  const result = to5.transform(code, {
    whitelist: ["nonexistentTransformer"]
  });
} catch (err) {
  if (err instanceof ReferenceError && err.message.includes("Unknown transformer")) {
    console.error("Check transformer names against available transformers");
    console.log("Available transformers:", Object.keys(to5.transformers));
  }
}