or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-features.mdast-nodes.mdcode-generation.mdformatting-options.mdindex.mdsource-maps.md
tile.json

code-generation.mddocs/

Code Generation

Core API for converting Abstract Syntax Trees (ASTs) into JavaScript code with customizable formatting and source map options.

Capabilities

Generate Function

The main function for converting ASTs to code. Accepts an AST, optional formatting options, and optional source code for source map generation.

/**
 * Converts an AST into JavaScript code
 * @param ast - The AST to convert
 * @param opts - Optional formatting and source map options
 * @param code - Optional source code string or multi-source object for source maps
 * @returns Object containing generated code and optional source map
 */
function generate(
  ast: Object,
  opts?: GeneratorOptions,
  code?: string | Object
): GeneratorResult;

interface GeneratorResult {
  /** Generated JavaScript code */
  code: string;
  /** Source map object (lazy-loaded if sourceMaps enabled) */
  map?: Object;
  /** Raw mapping data for source maps */
  rawMappings?: Array<{
    generated: { line: number; column: number };
    original: { line: number; column: number };
    source: string;
    name?: string;
  }>;
}

Usage Examples:

import generate from "babel-generator";

// Basic usage
const result = generate(ast);
console.log(result.code);

// With formatting options
const result = generate(ast, {
  compact: false,
  quotes: "single",
  comments: true
});

// With source maps
const result = generate(ast, {
  sourceMaps: true,
  sourceMapTarget: "output.js",
  sourceFileName: "input.js"
}, sourceCode);

// Multi-source with source maps
const sources = {
  'module1.js': 'export const a = 1;',
  'module2.js': 'export const b = 2;'
};
const result = generate(combinedAst, { sourceMaps: true }, sources);

CodeGenerator Class

Class-based interface providing the same functionality as the generate function. Useful for cases where you need to maintain state or perform multiple operations.

/**
 * Class-based code generator interface
 */
class CodeGenerator {
  /**
   * Creates a new code generator instance
   * @param ast - The AST to convert
   * @param opts - Optional formatting and source map options  
   * @param code - Optional source code for source maps
   */
  constructor(ast: Object, opts?: GeneratorOptions, code?: string | Object);
  
  /**
   * Generates code from the configured AST
   * @returns Object containing generated code and optional source map
   */
  generate(): GeneratorResult;
}

Usage Examples:

import { CodeGenerator } from "babel-generator";

// Class-based usage
const generator = new CodeGenerator(ast, {
  minified: true,
  comments: false
});

const result = generator.generate();
console.log(result.code);

// Different generators for different options
const minifiedGenerator = new CodeGenerator(ast, { minified: true });
const minified = minifiedGenerator.generate();

const formattedGenerator = new CodeGenerator(ast, { compact: false });
const formatted = formattedGenerator.generate();

Generation Options Interface

Complete interface definition for all available generation options.

interface GeneratorOptions extends FormatOptions, SourceMapOptions {
  /** Comment at the beginning of generated code */
  auxiliaryCommentBefore?: string;
  
  /** Comment at the end of generated code */
  auxiliaryCommentAfter?: string;
  
  /** Function to filter which comments to include */
  shouldPrintComment?: (comment: string) => boolean;
  
  /** Preserve original line numbers when possible */
  retainLines?: boolean;
  
  /** Keep parentheses around function expressions */
  retainFunctionParens?: boolean;
  
  /** Include comments in output */
  comments?: boolean;
  
  /** Minimize whitespace (true/false/"auto") */
  compact?: boolean | "auto";
  
  /** Full minification mode */
  minified?: boolean;
  
  /** Reduce unnecessary whitespace */
  concise?: boolean;
  
  /** Quote style for strings */
  quotes?: "single" | "double";
  
  /** Filename for error messages */
  filename?: string;
  
  /** Use commas instead of semicolons in Flow */
  flowCommaSeparator?: boolean;
  
  /** Generate JSON-compatible strings */
  jsonCompatibleStrings?: boolean;
}

interface FormatOptions {
  compact?: boolean | "auto";
  minified?: boolean;
  concise?: boolean;
  quotes?: "single" | "double";
  retainLines?: boolean;
  retainFunctionParens?: boolean;
  comments?: boolean;
  auxiliaryCommentBefore?: string;
  auxiliaryCommentAfter?: string;
  shouldPrintComment?: (comment: string) => boolean;
  filename?: string;  
  flowCommaSeparator?: boolean;
  jsonCompatibleStrings?: boolean;
}

interface SourceMapOptions {
  /** Enable source map generation */
  sourceMaps?: boolean;
  
  /** Filename for generated code */
  sourceMapTarget?: string;
  
  /** Root path for source map */
  sourceRoot?: string;
  
  /** Original source filename */
  sourceFileName?: string;
}

Error Handling

The generator may throw errors for invalid ASTs or configuration issues.

// Common error scenarios:
// - Invalid AST structure
// - Unsupported node types
// - Invalid configuration options
// - Source map generation failures

try {
  const result = generate(ast, options);
} catch (error) {
  console.error('Generation failed:', error.message);
}