recast

repository·master·Indexed 26 days ago

https://github.com/benjamn/recast

A JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator. Recast specializes in 'conservative reprinting', allowing developers to manipulate Abstract Syntax Trees (ASTs) while preserving the original formatting of unmodified code sections. It supports custom parsers for TypeScript, Flow, and Babel, and provides utilities for parsing, printing, and traversing ASTs via a visitor pattern.

Tokens
2.7K
Snippets
4
Records
22
Agent score
90%

What's inside recast

  1. Import recast

    master

    Recast is designed to be used with named imports in ESM or via require in CommonJS.

    ESM (Named imports):

    import { parse, print } from "recast";

    ESM (Namespace import):

    import * as recast from "recast";

    CommonJS:

    const { parse, print } = require("recast");
    import { parse, print } from "recast";
  2. Install recast

    master

    You can install recast via npm or by cloning the repository from GitHub.

    From npm:

    npm install recast

    From GitHub:

    cd path/to/node_modules
    git clone git://github.com/benjamn/recast.git
    cd recast
    npm install .
    npm install recast
  3. Parse and reprint JavaScript code

    master

    Recast provides two primary interfaces: parse to convert source code into an Abstract Syntax Tree (AST), and print to convert a modified AST back into source code.

    A key feature is conservative reprinting: Recast only reprints the parts of the tree you modified, preserving the original formatting of unmodified sections. If you want to discard original formatting and use a generic pretty printer, use recast.prettyPrint instead.

  4. Use a different parser with recast.parse

    master

    By default, Recast uses esprima. To support TypeScript, Flow, or Babel, you can pass a different parser in the options object.

    Important: To ensure conservative reprinting works, you must call recast.parse rather than using the external parser directly. This allows Recast to create a shadow copy of the AST with .original properties.

    Using a custom parser object:

    const ast = recast.parse(source, {
      parser: {
        parse(source) {
          return require("acorn").parse(source, { /* options */ });
        }
      }
    });

    Using preconfigured parsers: Recast provides preconfigured parsers for common syntaxes. Note that you may need to manually install the underlying parser (e.g., @babel/parser or acorn) via npm.

    // For TypeScript
    const tsAst = recast.parse(source, {
      parser: require("recast/parsers/typescript")
    });
    const tsAst = recast.parse(source, {
      parser: require("recast/parsers/typescript")
    });
  5. Generate source maps

    master

    Recast can automatically generate high-resolution source maps that map the generated code back to the original source files. To enable this, provide sourceFileName in the parse options and sourceMapName in the print options.

    var result = recast.print(recast.parse(source, {
      sourceFileName: "source.js"
    }), {
      sourceMapName: "source.min.js"
    });
    
    console.log(result.code); // The generated code
    console.log(result.map); // The JSON source map
    var result = recast.print(recast.parse(source, {
      sourceFileName: "source.js"
    }), {
      sourceMapName: "source.min.js"
    });
    
    console.log(result.code);
    console.log(result.map);
  6. Configure printing options for code generation

    master

    When printing an AST back to source code, you can pass an options object to control formatting. The following keys are used by the printer:

    • wrapColumn: The maximum line length before the printer attempts to wrap code (e.g., function arguments or parameters).
    • tabWidth: The number of spaces used for indentation.
    • objectCurlySpacing: A boolean that determines whether to include spaces inside curly braces (e.g., { x } vs {x}).
    • quote: Controls how string literals are quoted. Supported values:
      • "auto": Chooses between single or double quotes based on which results in a shorter string.
      • "single": Forces single quotes.
      • "double": Forces double quotes (default).
    • parameters: (Contextual) Used to determine if trailing commas should be enabled in parameter lists.
  7. Configure Recast parsing and printing options

    master
    All Recast API functions accept a second parameter containing a configuration object of type Options. This object allows you to control the parser used, indentation styles, whitespace handling, source map generation, and various code formatting rules during reprinting.
  8. Configure run output with RunOptions

    master
    When using run(), you can provide RunOptions to control behavior. The writeback property allows you to define a custom function to handle the output string (e.g., writing to a file instead of stdout).
  9. Printer behavior for unknown or unsupported types

    master
    If the printer encounters an AST node type that is not explicitly handled in its internal dispatch logic (including various XML-related nodes or unimplemented class heritage/comprehension nodes), it will throw an error: unknown type: <json_representation_of_type>. To avoid this, ensure all nodes in your AST are either supported or have been transformed into supported types.
  10. Convert an AST back to source code with Printer

    master

    The Printer class is used to convert an Abstract Syntax Tree (AST) back into source code. You can instantiate a Printer with an optional configuration object and use its .print(ast) method to generate code.

    Note that .print() returns a PrintResultType object, not a raw string. While the object has a .toString() method that returns the code, it is strongly discouraged to treat the result as a string directly. Instead, access the .code property.

  11. Reprint a modified AST with print()

    master
    Use print to convert a modified AST back into a string. print attempts to reuse as much of the original source code as possible (preserving formatting, comments, and whitespace) for the parts of the tree that were not changed.