is-reference AST Node Identification

3.0.3 · active · verified Sun Apr 19

is-reference is a focused utility designed to accurately determine whether a given JavaScript Abstract Syntax Tree (AST) node, specifically an `Identifier`, constitutes a 'reference' in the context of scope analysis. This is crucial for tools like bundlers, minifiers, and linters that need to differentiate between identifiers that refer to a variable binding (e.g., `console.log(foo)`) and those that are property names (e.g., `obj.foo`). The package is currently at version 3.0.3 and appears to follow an infrequent release cadence, driven by the needs of projects like Rollup. Its primary differentiator is its precise definition of a 'reference' within the ESTree specification, distinguishing it from simply being an `Identifier` node. It ships with TypeScript types, ensuring type-safe usage in modern JavaScript environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to parse an AST using Acorn, walk it with estree-walker, and identify 'reference' nodes using `is-reference`, distinguishing them from mere identifier occurrences within the AST.

import { parse } from 'acorn';
import { walk } from 'estree-walker';
import is_reference from 'is-reference';

const identifiers = [];
const references = [];

// Using ecmaVersion to support modern syntax for the AST parsing
const ast = parse(`
  const x = 1;
  let y = x + obj.prop;
  function foo(param) { console.log(param, y); }
  foo(x);
`, { ecmaVersion: 2020 });

walk(ast, {
	enter(node, parent) {
		if (node.type === 'Identifier') identifiers.push(node);
		if (is_reference(node, parent)) references.push(node);
	}
});

console.log('All Identifiers:', identifiers.map(node => node.name).join(', '));
// Expected: All Identifiers: x, y, x, obj, prop, foo, param, console, log, param, y, foo, x

console.log('References:', references.map(node => node.name).join(', '));
// Expected: References: x, y, x, obj, foo, param, console, log, param, y, foo, x

view raw JSON →