https://github.com/codemodsquad/jscodeshift-find-imports
find imported/required identifiers with jscodeshift
https://github.com/codemodsquad/jscodeshift-find-imports
imports jscodeshift
Last synced: 5 months ago
JSON representation
find imported/required identifiers with jscodeshift
- Host: GitHub
- URL: https://github.com/codemodsquad/jscodeshift-find-imports
- Owner: codemodsquad
- License: mit
- Created: 2019-05-17T19:16:03.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2023-01-06T01:51:04.000Z (over 2 years ago)
- Last Synced: 2024-04-14T09:40:41.377Z (about 1 year ago)
- Topics: imports, jscodeshift
- Language: JavaScript
- Homepage:
- Size: 1.07 MB
- Stars: 12
- Watchers: 2
- Forks: 2
- Open Issues: 21
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# jscodeshift-find-imports
[](https://circleci.com/gh/codemodsquad/jscodeshift-find-imports)
[](https://codecov.io/gh/codemodsquad/jscodeshift-find-imports)
[](https://github.com/semantic-release/semantic-release)
[](http://commitizen.github.io/cz-cli/)
[](https://badge.fury.io/js/jscodeshift-find-imports)find imported/required identifiers with jscodeshift
# Usage
```
npm i jscodeshift-find-imports
``````js
const findImports = require('jscodeshift-find-imports')
const j = require('jscodeshift')
const { statement } = j.templateconst code = `
import bar from 'foo'
`const imports = findImports(j(code), statement`import foo from 'foo'`)
console.log(imports) // {foo: {type: 'Identifier', name: 'bar'}}
```# Compatibility
Currently tested and working with `[email protected]` and the following parsers:
* `'babel'`
* `'babylon'`
* `'ts'`
* `'flow'`It won't likely work with other custom parsers unless they output nodes in the same format as
Babel for import declarations, variable declarations, require calls, and object patterns.# `findImports(root, statements)`
## Arguments
### `root`
The jscodeshift-wrapped AST of source code
### `statements`
The AST of an `ImportDeclaration` or `VariableDeclaration` containing `require`
calls to search for (e.g. `const foo = require('foo')`), or an array of them.## Returns
An object where each key is an identifier from your search statement(s) that was found, and the
corresponding value is the AST for the local binding for that import (either an `Identifier` or
`MemberExpression` node). For example, if you search for `const {bar} = require('bar')` but the
source code has `const foo = require('bar').bar`, the result will have `bar: { type: 'Identifier', name: 'bar' }`.The local binding will be a `MemberExpression` in cases like this:
```js
const code = `
import React from 'react'
`
const imports = findImports(
j(code),
statement`import { Component } from 'react'`
)
```In this case `imports` would be
```js
{
Component: {
type: 'MemberExpression',
object: {
type: 'Identifier',
name: 'React',
},
property: {
type: 'Identifier',
name: 'Component',
},
},
}
```