Find Import Usage
Description
It is common to find the usage of an imported module in a codebase. This rule helps you to find the usage of an imported module in your codebase. The idea of this rule can be broken into several parts:
- Find the use of an identifier
$MOD
- To find the import, we first need to find the root file of which
$MOD
isinside
- The
program
filehas
animport
statement - The
import
statementhas
the identifier$MOD
YAML
yaml
id: find-import-usage
language: typescript
rule:
kind: identifier # ast-grep requires a kind
pattern: $MOD # the identifier to find
inside: # find the root
stopBy: end
kind: program
has: # and has the import statement
kind: import_statement
has: # look for the matching identifier
stopBy: end
kind: import_specifier
pattern: $MOD # same pattern as the usage is enforced here
Example
ts
import { MongoClient } from 'mongodb';
const url = 'mongodb://localhost:27017';
async function run() {
const client = new MongoClient(url);
}