@nodejs/codemod-utils package provides a comprehensive set of utilities for building Node.js codemods with ast-grep. These utilities handle complex patterns for import/require analysis, binding resolution, code transformation, and package.json processing.
Why Use These Utilities?
Building Node.js codemods requires handling complex patterns for:- Import/Require Analysis: Finding and analyzing
importstatements andrequire()calls for specific modules - Binding Resolution: Determining how imported functions are accessed locally (destructured, aliased, etc.)
- Code Transformation: Safely removing unused imports and modifying code while preserving formatting
- Package.json Processing: Analyzing and transforming
package.jsonscripts that use Node.js
API Categories
Import and Require Detection
Utilities for finding and analyzing module dependencies:- getModuleDependencies - Find all import/require statements for a module
- getNodeImportStatements - Find ES module import statements
- getNodeImportCalls - Find dynamic import calls
- getNodeRequireCalls - Find CommonJS require calls
Binding Resolution and Transformation
Utilities for resolving and manipulating import bindings:- resolveBindingPath - Resolve global API paths to local bindings
- removeBinding - Remove specific bindings from imports
- updateBinding - Update or replace bindings
AST-grep Helper Functions
Core utilities for working with AST nodes:- detectIndentUnit - Detect indentation style
- getLineIndent - Get indentation for a specific line
- getShebang - Find Node.js shebang lines
- getScope - Find enclosing scope for a node
- removeLines - Safely remove line ranges
- getDefaultImportIdentifier - Get default import identifier
- getRequireNamespaceIdentifier - Get namespace require identifier
- replaceNodeJsArgs (shebang) - Replace Node.js args in shebangs
Package.json Utilities
Utilities for processing package.json files:- removeDependencies - Remove dependencies from package.json
- getScriptsNode - Find the scripts section
- getNodeJsUsage - Find Node.js usage in scripts
- replaceNodeJsArgs - Replace Node.js arguments in scripts
- removeNodeJsArgs - Remove Node.js arguments from scripts
Type Definitions
All utilities use types from@codemod.com/jssg-types:
SgRoot<Js>- Root AST node for JavaScript/TypeScriptSgNode<Js>- Individual AST nodeEdit- Represents a code edit operationRange- Represents a position range in source code