escodegen Documentation

repository·master·Indexed 25 days ago

https://github.com/estools/escodegen

An ECMAScript (JavaScript) code generator that converts Mozilla Parser API ASTs into source code strings. It provides a `generate()` method for AST-to-code conversion, supports a wide range of statement and expression types, and includes CLI tools (`escodegen` and `esgenerate`) for generating code from AST files. The library supports customizable formatting options for indentation, quoting, and minification, as well as source map generation and comment attachment.

Tokens
2.9K
Snippets
6
Records
18
Agent score
82%

What's inside escodegen

  1. Build browser or minified browser bundles

    master

    If you are developing with the repository, you can generate the browser-ready files using the following steps:

    1. Install dev dependencies: npm install
    2. Generate the standard browser bundle: npm run-script build (creates escodegen.browser.js)
    3. Generate the minified browser bundle: npm run-script build-min (creates escodegen.browser.min.js)
    npm install
    npm run-script build
    npm run-script build-min
  2. Use escodegen in a web browser

    master

    To use escodegen in a browser environment, include the escodegen.browser.js script in your HTML. You can find this file in the tagged revisions on GitHub.

    <script src="escodegen.browser.js"></script>
  3. Generate code using escodegen.generate()

    master

    Use the escodegen.generate() method to convert a Mozilla Parser API AST into an ECMAScript (JavaScript) code string. Pass an object representing the AST node to the function.

    escodegen.generate({
        type: 'BinaryExpression',
        operator: '+',
        left: { type: 'Literal', value: 40 },
        right: { type: 'Literal', value: 2 }
    });
    // produces the string '40 + 2'
  4. Configure code generation via options

    master

    The generate function accepts an options object to control the output format.

    Key Configuration Areas:

    Format Options (options.format)

    • compact: If true, removes newlines, spaces, and indentation (useful for minification).
    • indent: Controls indentation style and depth.
      • style: The string used for indentation (e.g., ' ', '\t').
      • base: The number of times the style is repeated.
    • quotes: Controls string quoting ('double', 'single', or 'auto').
    • semicolons: Controls whether semicolons are added.
    • parentheses: Controls whether parentheses are used for grouping.
    • hexadecimal: Boolean for hexadecimal representation (used in JSON mode).
    • json: If true, the generator behaves in JSON mode (uses double quotes, no semicolons, etc.).
    • renumber: Boolean for renumbering.
    • escapeless: Boolean for escaping characters.
    • newline: The character used for newlines.
    • space: The character used for spacing.
    • preserveBlankLines: Boolean; works only if sourceCode is provided.

    Other Options

    • sourceMap: Boolean to enable source map generation.
    • sourceMapWithCode: Boolean; if true, returns an object containing both the code and the map.
    • sourceCode: The original source code string (required for preserveBlankLines).
    • directive: Custom directive for the generator.
    • parse: A custom parser function for handling raw properties in literals.
    • file: Filename for the source map.
    • sourceMapRoot: Root URL for the source map.
  5. Configure escodegen generation options

    master

    When using escodegen, you can pass an options object to control the output format. Key configuration areas include:

    • format: Controls code style:
      • indent: An object with style (e.g., ' '), base (starting indentation level), and adjustMultilineComment (boolean).
      • newline: The character used for newlines (default \n).
      • space: The character used for spacing (default ' ').
      • quotes: String literal quoting style ('single', 'double', or 'auto').
      • semicolons: Boolean to enable/disable semicolons.
      • compact: Boolean for minified-style output.
      • json: Boolean to format output as JSON.
      • parentheses: Boolean to control wrapping in parentheses.
    • moz: Specific options for Mozilla-style generator behavior:
      • starlessGenerator: Boolean.
      • comprehensionExpressionStartsWithAssignment: Boolean.
    • sourceMap: Can be a boolean or a configuration object for generating source maps.
    • comment: Boolean to enable/disable comment generation.
    const options = {
        format: {
            indent: {
                style: '    ',
                base: 0,
                adjustMultilineComment: false
            },
            newline: '\n',
            space: ' ',
            json: false,
            renumber: false,
            hexadecimal: false,
            quotes: 'single',
            escapeless: false,
            compact: false,
            parentheses: true,
            semicolons: true,
            safeConcatenation: false,
            preserveBlankLines: false
        },
        moz: {
            comprehensionExpressionStartsWithAssignment: false,
            starlessGenerator: false
        },
        sourceMap: null,
        sourceMapRoot: null,
        sourceMapWithCode: false,
        directive: false,
        raw: true,
        verbatim: null,
        sourceCode: null
    };
  6. Generate code from an AST using generate()

    master

    The generate(node, options) function is the primary API for converting an Abstract Syntax Tree (AST) node into a string of source code. It supports both statements and expressions. If options.sourceMap is enabled, it can return source maps and source content.

    Return Values:

    • If options.sourceMap is false (default): Returns the code as a string, or an object {code: string, map: null} if options.sourceMapWithCode is true.
    • If options.sourceMap is true: Returns the source map as a string, or an object {code: string, map: SourceNode} if options.sourceMapWithCode is true.
  7. Generate code from an AST using escodegen

    master
    The escodegen library provides a mechanism to convert an Abstract Syntax Tree (AST) into formatted JavaScript code. The core functionality is driven by the generate() method (implied by the entrypoint role), which traverses the AST nodes and applies specific generation rules for each node type (Statements and Expressions).
  8. Attach comments to AST nodes

    master
    Use attachComments(ast) to attach comments to the provided AST. This is a wrapper around estraverse.attachComments and is required if you want the generate function to include comments in the output (provided extra.comment is enabled in options).