Babel Literal to AST

2.1.0 · maintenance · verified Sun Apr 19

This utility package, `babel-literal-to-ast`, converts standard JavaScript literals and simple objects directly into their Abstract Syntax Tree (AST) representation, formatted according to Babel's specific AST specification. Unlike general-purpose AST parsers that convert source code strings, this library takes a live JavaScript value (like a number, string, boolean, array, or plain object) and returns the corresponding Babel AST node structure. It currently sits at version 2.1.0, with its last update in February 2019, suggesting a stable but no longer actively developed status. Its primary use case is within Babel transformers or other tools that manipulate Babel ASTs, providing a convenient way to inject or create AST nodes from known literal values without having to manually construct the AST objects or parse stringified code. A key differentiator is its direct output to Babel AST format, which has specific deviations from the more generic ESTree specification.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates converting various JavaScript literals and objects into their Babel AST representation and then generating code from them using `@babel/generator`.

import serialize from 'babel-literal-to-ast';
import generate from '@babel/generator';

// Basic literal: string
let astString = serialize('Hello, Babel!');
console.log('String AST:', generate(astString).code);
// Expected output: String AST: "Hello, Babel!"

// Basic literal: number
let astNumber = serialize(12345);
console.log('Number AST:', generate(astNumber).code);
// Expected output: Number AST: 12345

// Object literal
let astObject = serialize({
  message: 'Hello',
  version: 2.1,
  enabled: true,
  items: [1, 'two', null]
});
console.log('Object AST:', generate(astObject).code);
/* Expected output:
Object AST: ({ message: 'Hello', version: 2.1, enabled: true, items: [1, 'two', null] });
(Note: The wrapping parentheses are often added by @babel/generator for ExpressionStatement compatibility.)
*/

// Null and undefined (undefined usually becomes Identifier 'undefined')
let astNull = serialize(null);
let astUndefined = serialize(undefined);
console.log('Null AST:', generate(astNull).code);
console.log('Undefined AST:', generate(astUndefined).code);
// Expected output: Null AST: null
// Expected output: Undefined AST: undefined

view raw JSON →