scope-analyzer is a JavaScript library designed for performing basic scope analysis on JavaScript Abstract Syntax Trees (ASTs). It tracks variable scopes and collects references to variables within a given AST, enabling tasks like refactoring, renaming, and understanding variable usage patterns. The current stable version is 2.1.2. The package has seen consistent minor and patch releases, indicating active maintenance, though its stability badge still labels it as "experimental." A key differentiator is its focus on simplicity and direct manipulation of AST nodes, providing methods to crawl the tree, create, delete, and inspect scopes, and retrieve bindings and references. It is particularly useful for tools that need to understand the lexical environment of JavaScript code. It expects AST nodes to have a `.parent` property, often requiring a pre-processing step with utilities like `estree-assign-parent`.
npm install scope-analyzerVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to parse a JavaScript string into an AST using Acorn, prepare it for `scope-analyzer` (potentially by assigning parent nodes), then define global variables with `createScope` and analyze the AST with `crawl`. It illustrates how to retrieve a specific binding (e.g., `exports`) and iterate over its references, as well as how to find undeclared names within a given scope.
Before passing your AST to `scope-analyzer`, use a utility like `estree-assign-parent` to add parent references to all nodes. Example: `require('estree-assign-parent')(ast);`If `recast` compatibility is not a concern and performance is critical, consider pinning your dependency to version `2.1.1`. Otherwise, be aware of the potential performance impact when using or upgrading to `>=2.1.2`.
Exercise caution when relying on specific internal implementations or undocumented features. Regularly review release notes for updates and potential breaking changes, even in minor versions.
When using `scan.getBinding()`, always check `binding.definition` if you need to distinguish between formally declared variables and implicitly used (undeclared) identifiers.
In ES Module projects, use dynamic `import()` (e.g., `const scan = await import('scope-analyzer');`) or ensure your build tooling correctly transpiles CommonJS `require` statements if you are using static `import` syntax.Preprocess your AST using a utility like `estree-assign-parent` to add the `.parent` property to all nodes. Example: `require('estree-assign-parent')(ast);`If in an ESM context, consider using dynamic `import()` (`const scan = await import('scope-analyzer');`) or configure your bundler/Node.js environment to properly handle CommonJS modules.Ensure you are using the correct CommonJS import: `const scan = require('scope-analyzer');`. Avoid named imports (`import { crawl } from 'scope-analyzer';`) as the package exports a single object.No dependency data recorded yet.