Detect Global Variables in JavaScript ASTs

7.0.1 · active · verified Sun Apr 19

acorn-globals is a utility for identifying global variable references within JavaScript code by leveraging the Acorn AST parser. It traverses the Abstract Syntax Tree (AST) generated by Acorn to distinguish between locally declared variables and those that implicitly refer to the global scope. The package is currently at version 7.0.1 and appears to maintain an active release cadence, primarily driven by updates to its underlying Acorn dependency and bug fixes related to scope resolution (e.g., switch statement bodies, catch handlers). Its key differentiator is its focus solely on global variable detection based on AST analysis, providing precise lexical scope information without performing any runtime evaluation. It is particularly useful for static analysis tools, linters, and bundlers that need to understand variable leakage or undeclared globals.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `acorn-globals` to parse a JavaScript string and identify all implicit global variable references, logging their names and their respective AST node positions.

import fs from 'node:fs';
import path from 'node:path';
import detect from 'acorn-globals';

// Create a dummy input file for demonstration
const inputJsPath = path.join(process.cwd(), 'input.js');
const srcContent = `
var x = 5;
var y = 3, z = 2;

w.foo();
w = 2;

RAWR=444;
RAWR.foo();

BLARG=3;

foo(function () {
    var BAR = 3;
    process.nextTick(function (ZZZZZZZZZZZZ) {
        console.log('beep boop');
        var xyz = 4;
        x += 10;
        x.zzzzzz;
        ZZZ=6;
    });
    function doom () {
    }
    ZZZ.foo();

});

console.log(xyz);
`;

fs.writeFileSync(inputJsPath, srcContent, 'utf8');

// Read the source code
const src = fs.readFileSync(inputJsPath, 'utf8');

// Detect global variables
const scope = detect(src);

console.log('Detected globals:');
scope.forEach(globalVar => {
  console.log(`- ${globalVar.name} (found at positions: ${globalVar.nodes.map(node => node.start).join(', ')})`);
});

// Clean up the dummy file
fs.unlinkSync(inputJsPath);

view raw JSON →