### Source Map Configuration Example Source: https://github.com/estools/escodegen/wiki/Source-Map-Usage Example of configuring source map options. The `sourceMap` option can be a string for a filename or `true`. The `sourceMapRoot` option sets the base path for source files referenced in the map. ```javascript { sourceMap: 'foo.js', sourceRoot: '/static/js' } ``` -------------------------------- ### Install Escodegen via npm Source: https://github.com/estools/escodegen/blob/master/README.md Use this command to install the package in a Node.js application. ```bash npm install escodegen ``` -------------------------------- ### Generate Code and Source Map for Multiple Files Source: https://github.com/estools/escodegen/wiki/Source-Map-Usage This example demonstrates how to generate code and a source map that correctly references multiple source files. It involves parsing code from different files, combining their ASTs, and then generating the output with source map options enabled. ```javascript var ast1 = acorn.parse('var a = 1', { locations: true, sourceFile: 'a.js' }); var ast2 = esprima.parse('var b = 1', { loc: true, source: 'b.js' }); var astBoth = { type: 'Program', body: [].concat(ast1.body).concat(ast2.body) }; var output = escodegen.generate(astBoth, { sourceMap: true, sourceMapWithCode: true }); var code = output.code; var map = output.map.toString(); // Map will now properly point to both a.js and b.js where // appropriate. ``` -------------------------------- ### Generate Code and Source Map with Esprima Source: https://github.com/estools/escodegen/wiki/Source-Map-Usage This example shows how to generate code and source maps using the Esprima parser. Configure Esprima with 'loc' and 'source' options for proper source map generation. ```javascript var ast = esprima.parse('var a = 1', { loc: true, source: 'my_file.js' }); var output = escodegen.generate(ast, { sourceMap: true, // Settings source in esprima's options gives us // filenames already. sourceMapWithCode: true // Get both code and source map }); var code = output.code; // Generated source code var map = output.map.toString(); // Generated source map JSON ``` -------------------------------- ### Embed Source Code in Source Map Source: https://github.com/estools/escodegen/wiki/Source-Map-Usage This example shows how to embed the original source code directly into the generated source map by providing the 'sourceContent' option. This is useful when the original source file may not be publicly accessible. ```javascript var code = 'var a = 1;\n\n\nvar b = 1;' var ast = acorn.parse(code, { locations: true, sourceFile: 'foo.js' }); var output = escodegen.generate(ast, { sourceMap: true, sourceMapWithCode: true, sourceContent: code }); var newCode = output.code; // Does not include the extra newlines! var map = output.map.toString(); // The map will now refer back to code, but the code file doesn't need // to be publicly accessible because it's included in the output. ``` -------------------------------- ### Build Browser Bundles Source: https://github.com/estools/escodegen/blob/master/README.md Use npm scripts to generate browser-compatible versions of the library. ```bash npm run-script build ``` ```bash npm run-script build-min ``` -------------------------------- ### Configure code formatting options Source: https://context7.com/estools/escodegen/llms.txt Customize indentation, whitespace, and stylistic preferences using the format object. Presets like FORMAT_DEFAULTS and FORMAT_MINIFY are available for quick configuration. ```javascript const escodegen = require('escodegen'); const ast = { type: 'Program', body: [{ type: 'BlockStatement', body: [{ type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'test' } }] }] }; // Custom 2-space indentation const twoSpaceCode = escodegen.generate(ast, { format: { indent: { style: ' ', // 2 spaces base: 0 // Base indent level } } }); console.log(twoSpaceCode); // Output: // { // test; // } // Tab indentation with base level const tabbedCode = escodegen.generate(ast, { format: { indent: { style: '\t', base: 1 } } }); // Full format options example const customCode = escodegen.generate(ast, { format: { indent: { style: ' ', // 4 spaces (default) base: 0, // Base indent level adjustMultilineComment: true // Align multi-line comment asterisks }, newline: '\n', // Newline character space: ' ', // Space character json: false, // JSON format for literals renumber: false, // Optimize numeric literals hexadecimal: false, // Use hex for numbers when shorter quotes: 'single', // 'single', 'double', or 'auto' escapeless: false, // Minimal string escaping compact: false, // Remove whitespace parentheses: true, // Keep parentheses in new expressions semicolons: true, // Keep semicolons safeConcatenation: false // Safe script concatenation } }); // Using built-in presets console.log('Default format:', escodegen.FORMAT_DEFAULTS); console.log('Minify format:', escodegen.FORMAT_MINIFY); ``` -------------------------------- ### Generate Code from AST Source: https://context7.com/estools/escodegen/llms.txt Demonstrates the basic mapping of an AST structure to a JavaScript string output. ```javascript # "computed": false # }, # "arguments": [{ "type": "Literal", "value": "Hello World" }] # } # }] # } # Output: console.log('Hello World'); ``` -------------------------------- ### Configure generator options Source: https://github.com/estools/escodegen/wiki/API Default configuration object for formatting, source maps, and parser settings. ```js { 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 }, moz: { starlessGenerator: false, parenthesizedComprehensionBlock: false, comprehensionExpressionStartsWithAssignment: false }, parse: null, comment: false, sourceMap: undefined, sourceMapRoot: null, sourceMapWithCode: false, file: undefined, sourceContent: originalSource, directive: false, verbatim: undefined } ``` -------------------------------- ### Configure Escodegen Source Map Options Source: https://github.com/estools/escodegen/wiki/Source-Map-Usage Set source map generation options for Escodegen. Ensure `sourceMap` is truthy to enable source maps. Use `sourceMapRoot` to specify the root directory for source files and `sourceContent` to embed source code directly into the map. ```javascript escodegen.generate(ast, { sourceMap: undefined, // true or string sourceMapRoot: null, // Root directory for sourceMap sourceMapWithCode: false, // Set to true to include code AND source map sourceContent: undefined, // If set, embedded in source map as code // Other configuration options... }); ``` -------------------------------- ### Complete AST Transformation Pipeline Source: https://context7.com/estools/escodegen/llms.txt A full workflow using Esprima for parsing, estraverse for AST modification, and Escodegen for generating code with source maps. ```javascript const esprima = require('esprima'); const estraverse = require('estraverse'); const escodegen = require('escodegen'); const originalSource = ` // Calculate sum of array function sum(arr) { var total = 0; for (var i = 0; i < arr.length; i++) { total += arr[i]; } return total; } `; // Step 1: Parse with full information const ast = esprima.parse(originalSource, { loc: true, range: true, tokens: true, comment: true, source: 'sum.js' }); // Attach comments to nodes escodegen.attachComments(ast, ast.comments, ast.tokens); // Step 2: Transform AST (convert var to let/const) estraverse.replace(ast, { enter: function(node) { if (node.type === 'VariableDeclaration' && node.kind === 'var') { // Check if variable is reassigned const isReassigned = node.declarations.some(d => d.id.name === 'total' || d.id.name === 'i' ); node.kind = isReassigned ? 'let' : 'const'; } return node; } }); // Step 3: Generate transformed code with source map const output = escodegen.generate(ast, { comment: true, format: { indent: { style: ' ' }, quotes: 'single', semicolons: true }, sourceMap: true, sourceMapWithCode: true, sourceContent: originalSource }); console.log('=== Generated Code ==='); console.log(output.code); console.log('\n=== Source Map ==='); console.log(output.map.toString()); // Output code: // // Calculate sum of array // function sum(arr) { // let total = 0; // for (let i = 0; i < arr.length; i++) { // total += arr[i]; // } // return total; // } ``` -------------------------------- ### Use Escodegen CLI Tools Source: https://context7.com/estools/escodegen/llms.txt Execute escodegen and esgenerate commands to process JavaScript files or AST JSON files with optional configuration. ```bash # escodegen: Parse JavaScript and regenerate # Usage: escodegen [options] file.js # Basic usage - regenerate formatted code escodegen input.js # With custom configuration file escodegen --config options.json input.js escodegen -c options.json input.js # Configuration file example (options.json): # { # "format": { # "indent": { "style": " " }, # "quotes": "double" # }, # "comment": true # } # esgenerate: Generate code from AST JSON # Usage: esgenerate [options] file.json # Generate from AST JSON file esgenerate ast.json # With configuration esgenerate --config options.json ast.json # Example AST JSON file (ast.json): # { # "type": "Program", # "body": [{ # "type": "ExpressionStatement", # "expression": { # "type": "CallExpression", # "callee": { # "type": "MemberExpression", # "object": { "type": "Identifier", "name": "console" }, # "property": { "type": "Identifier", "name": "log" }, ``` -------------------------------- ### Generate Code and Source Map with Acorn Source: https://github.com/estools/escodegen/wiki/Source-Map-Usage Use this snippet to generate JavaScript code and its corresponding source map when using the Acorn parser. Ensure Acorn is configured with 'locations' and 'sourceFile' options. ```javascript var ast = acorn.parse('var a = 1', { locations: true, sourceFile: 'my_file.js' }); var output = escodegen.generate(ast, { sourceMap: true, // Setting sourceFile in Acorn's options already // gives us filenames. sourceMapWithCode: true // Get both code and source map }); var code = output.code; // Generated source code var map = output.map.toString(); // Generated source map JSON ``` -------------------------------- ### Minify JavaScript output Source: https://context7.com/estools/escodegen/llms.txt Use the FORMAT_MINIFY preset or custom minification settings to produce compact code. Requires an AST generated by a parser like Esprima. ```javascript const escodegen = require('escodegen'); const esprima = require('esprima'); const source = ` function calculateTotal(items) { let total = 0; for (let i = 0; i < items.length; i++) { total += items[i].price * items[i].quantity; } return total; } `; const ast = esprima.parse(source); // Generate minified code const minified = escodegen.generate(ast, { format: escodegen.FORMAT_MINIFY }); console.log(minified); // Output: function calculateTotal(items){let total=0;for(let i=0;i x + y // Class definition const classAst = { type: 'ClassDeclaration', id: { type: 'Identifier', name: 'Animal' }, superClass: null, body: { type: 'ClassBody', body: [{ type: 'MethodDefinition', kind: 'constructor', key: { type: 'Identifier', name: 'constructor' }, value: { type: 'FunctionExpression', params: [{ type: 'Identifier', name: 'name' }], body: { type: 'BlockStatement', body: [{ type: 'ExpressionStatement', expression: { type: 'AssignmentExpression', operator: '=', left: { type: 'MemberExpression', object: { type: 'ThisExpression' }, property: { type: 'Identifier', name: 'name' } }, right: { type: 'Identifier', name: 'name' } } }] } }, computed: false, static: false }] } }; console.log(escodegen.generate(classAst)); // Output: // class Animal { // constructor(name) { // this.name = name; // } // } // Template literal const templateAst = { type: 'TemplateLiteral', quasis: [ { type: 'TemplateElement', value: { raw: 'Hello, ' } }, { type: 'TemplateElement', value: { raw: '!' }, tail: true } ], expressions: [ { type: 'Identifier', name: 'name' } ] }; console.log(escodegen.generate(templateAst)); // Output: `Hello, ${ name }!` // Destructuring assignment const destructureAst = { type: 'VariableDeclaration', kind: 'const', declarations: [{ type: 'VariableDeclarator', id: { type: 'ObjectPattern', properties: [ { type: 'Property', key: { type: 'Identifier', name: 'x' }, value: { type: 'Identifier', name: 'x' }, shorthand: true }, { type: 'Property', key: { type: 'Identifier', name: 'y' }, value: { type: 'Identifier', name: 'y' }, shorthand: true } ] }, init: { type: 'Identifier', name: 'point' } }] }; console.log(escodegen.generate(destructureAst)); // Output: const { x, y } = point; // Import/Export statements const importAst = { type: 'ImportDeclaration', specifiers: [{ type: 'ImportDefaultSpecifier', local: { type: 'Identifier', name: 'React' } }, { type: 'ImportSpecifier', imported: { type: 'Identifier', name: 'useState' }, local: { type: 'Identifier', name: 'useState' } }], source: { type: 'Literal', value: 'react' } }; console.log(escodegen.generate(importAst)); // Output: import React, { useState } from 'react'; ``` -------------------------------- ### Generate JavaScript Code from AST Source: https://context7.com/estools/escodegen/llms.txt Basic usage of escodegen.generate to convert a simple AST object into JavaScript code. Requires escodegen and esprima to be required. ```javascript const escodegen = require('escodegen'); const esprima = require('esprima'); // Basic usage: Generate code from AST const ast = { type: 'BinaryExpression', operator: '+', left: { type: 'Literal', value: 40 }, right: { type: 'Literal', value: 2 } }; const code = escodegen.generate(ast); console.log(code); // Output: '40 + 2' ``` ```javascript // Generate from parsed code with default formatting const sourceAst = esprima.parse('function hello(name) { return "Hello, " + name; }'); const generatedCode = escodegen.generate(sourceAst); console.log(generatedCode); // Output: // function hello(name) { // return 'Hello, ' + name; // } ``` ```javascript // Complete program generation const programAst = { type: 'Program', body: [{ type: 'VariableDeclaration', kind: 'const', declarations: [{ type: 'VariableDeclarator', id: { type: 'Identifier', name: 'x' }, init: { type: 'Literal', value: 42 } }] }, { type: 'ExpressionStatement', expression: { type: 'CallExpression', callee: { type: 'MemberExpression', object: { type: 'Identifier', name: 'console' }, property: { type: 'Identifier', name: 'log' }, computed: false }, arguments: [{ type: 'Identifier', name: 'x' }] } }] }; console.log(escodegen.generate(programAst)); // Output: // const x = 42; // console.log(x); ``` -------------------------------- ### Inject Verbatim Code with Escodegen Source: https://context7.com/estools/escodegen/llms.txt Use the `verbatim` option to inject custom code snippets directly into the output. This is useful for inserting pre-formatted or hand-optimized code segments. The `verbatim` option accepts a property name to look for on AST nodes, which contains the custom representation. ```javascript const escodegen = require('escodegen'); // Simple verbatim string replacement const ast = { type: 'Program', body: [{ type: 'ExpressionStatement', expression: { type: 'Literal', value: 200, 'x-verbatim-property': '2e2' // Custom representation } }] }; const output = escodegen.generate(ast, { verbatim: 'x-verbatim-property' }); console.log(output); // Output: 2e2 // Verbatim with precedence control const complexAst = { type: 'Program', body: [{ type: 'ExpressionStatement', expression: { type: 'BinaryExpression', operator: '*', left: { type: 'Literal', value: 10, 'x-custom': { content: '(5 + 5)', precedence: escodegen.Precedence.Primary } }, right: { type: 'Literal', value: 2 } } }] }; const complexOutput = escodegen.generate(complexAst, { verbatim: 'x-custom' }); console.log(complexOutput); // Output: (5 + 5) * 2 // Access precedence levels for proper grouping console.log(escodegen.Precedence); // { Sequence: 0, Assignment: 1, Conditional: 2, ... Primary: 22 } ``` -------------------------------- ### Generate Verbatim Code with String Source: https://github.com/estools/escodegen/wiki/API Use the verbatim option with a string value to directly output the specified string instead of generating code from the node's value. The option specifies which property on the node contains the verbatim string. ```javascript escodegen.generate({ type: 'Literal', value: 200, 'x-verbatim-property': '2e2' }, { verbatim: 'x-verbatim-property' }); ``` ```javascript 2e2 ``` -------------------------------- ### Include Escodegen in Browser Source: https://github.com/estools/escodegen/blob/master/README.md Add the script tag to your HTML file to use Escodegen in a web browser. ```html ``` -------------------------------- ### Generate Only Source Map Source: https://github.com/estools/escodegen/wiki/Source-Map-Usage Use this snippet to generate only the source map for a given AST, without generating the corresponding code. This is achieved by providing a filename string to the 'sourceMap' option. ```javascript var ast = acorn.parse('var a = 1', { locations: true }); var map = escodegen.generate(ast, { sourceMap: 'my.js' }); var json = map.toString(); // Convert the map to its JSON representation ``` -------------------------------- ### Generate Code from AST Source: https://github.com/estools/escodegen/blob/master/README.md Pass a Mozilla Parser API AST object to the generate method to produce a JavaScript code string. ```javascript escodegen.generate({ type: 'BinaryExpression', operator: '+', left: { type: 'Literal', value: 40 }, right: { type: 'Literal', value: 2 } }); ``` -------------------------------- ### Include Code and Source Map Source: https://github.com/estools/escodegen/wiki/Source-Map-Usage When `sourceMapWithCode` is set to `true`, Escodegen outputs an object containing both the generated code and the source map. This is useful for debugging generated code directly. ```javascript { code: ..., // Generated source code as a string map: ... // Generated source map, a SourceMapGenerator object } ``` -------------------------------- ### Preserve comments in generated code Source: https://context7.com/estools/escodegen/llms.txt Attach comments to the AST using attachComments() before generation. Requires parsing with comment, token, and range information enabled. ```javascript const escodegen = require('escodegen'); const esprima = require('esprima'); const source = ` // Initialize counter var counter = 0; /* Increment function * Adds one to counter */ function increment() { counter++; // Increase by one } `; // Parse with comments, tokens, and ranges const ast = esprima.parse(source, { comment: true, tokens: true, range: true }); // Attach comments to AST nodes escodegen.attachComments(ast, ast.comments, ast.tokens); // Generate with comment preservation const output = escodegen.generate(ast, { comment: true }); console.log(output); // Output preserves all comments in their original positions: // // Initialize counter // var counter = 0; // /* Increment function // * Adds one to counter // */ // function increment() { // counter++; // Increase by one // } // Preserve blank lines from original source const outputWithBlanks = escodegen.generate(ast, { comment: true, format: { preserveBlankLines: true }, sourceCode: source // Required for blank line preservation }); ``` -------------------------------- ### escodegen.generate Function Source: https://github.com/estools/escodegen/wiki/API The primary function for generating JavaScript code from an AST. It accepts the AST and an optional options object. ```APIDOC ## escodegen.generate(AST[, options]) ### Description Generates JavaScript code from an Abstract Syntax Tree (AST). ### Method Function Call ### Parameters #### Path Parameters - **AST** (object) - Required - The Abstract Syntax Tree to convert into code. - **options** (object) - Optional - Configuration options for the code generation process. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.