Convert JavaScript values to ESTree expressions

3.5.0 · active · verified Sun Apr 19

estree-util-value-to-estree is a utility library for converting diverse JavaScript values into their corresponding ESTree Abstract Syntax Tree (AST) expressions. This package is particularly useful for tools that manipulate or generate JavaScript code, enabling programmatic construction of AST nodes from native JavaScript types. The current stable version is 3.5.0, with a release cadence that includes regular minor and patch updates to support new JavaScript features and fix bugs. Key differentiators include its broad support for various primitive types (e.g., bigint, symbol, undefined, null, boolean, number, string) and object types (e.g., Array, Object, Map, Set, Date, RegExp, Buffer, various TypedArrays, and Temporal types). It also provides a `serialize` option for handling custom or unsupported values, allowing users to define how complex or application-specific data structures should be represented in the AST. It is designed for values that can be constructed without needing a runtime context.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates converting a complex JavaScript object into an ESTree expression, then generating JavaScript code from that ESTree. It includes an example of using the `serialize` option to handle custom class instances and `Buffer` objects, which are not natively supported as simple literals.

import { valueToEstree } from 'estree-util-value-to-estree';
import { generate } from 'astring'; // Commonly used to convert ESTree to code

const exampleValue = {
  id: 123,
  name: 'Example Item',
  enabled: true,
  price: 99.95,
  details: ['alpha', 'beta', null],
  config: new Map([['key1', 'value1'], ['key2', 42n]]),
  created: new Date('2024-01-01T10:00:00Z'),
  pattern: /test/g,
  complex: {
    nested: Symbol.for('unique-id'),
    buffer: Buffer.from('hello'),
    // Unsupported types will require a custom serializer
    customClass: new class MyCustom { constructor() { this.prop = 'value'; } }()
  }
};

// Convert a standard JavaScript value to an ESTree expression
const estreeExpression = valueToEstree(exampleValue);
console.log('Generated ESTree (partial):', estreeExpression.type);
console.log('Generated Code for standard value:\n', generate(estreeExpression));

// Example with a custom serializer for the custom class
const estreeWithCustom = valueToEstree(exampleValue, {
  serialize(value) {
    if (value instanceof Buffer) {
      // Convert Buffer to a Buffer.from() call
      return {
        type: 'CallExpression',
        callee: { type: 'MemberExpression', object: { type: 'Identifier', name: 'Buffer' }, property: { type: 'Identifier', name: 'from' }, computed: false, optional: false },
        arguments: [{ type: 'Literal', value: value.toString('hex') }, { type: 'Literal', value: 'hex' }]
      };
    }
    if (value && typeof value === 'object' && value.constructor.name === 'MyCustom') {
      // Convert MyCustom instance to a new MyCustom() expression
      return {
        type: 'NewExpression',
        callee: { type: 'Identifier', name: 'MyCustom' },
        arguments: []
      };
    }
    // Let the default logic handle other types
    return undefined;
  }
});
console.log('\nGenerated Code with custom serializer:\n', generate(estreeWithCustom));

view raw JSON →