jscodeshift-find-imports
TypeScript icon, indicating that this package has built-in type declarations

2.0.4 • Public • Published

jscodeshift-find-imports

CircleCI Coverage Status semantic-release Commitizen friendly npm version

find imported/required identifiers with jscodeshift

Usage

npm i jscodeshift-find-imports
const findImports = require('jscodeshift-find-imports')
const j = require('jscodeshift')
const { statement } = j.template

const 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 jscodeshift@0.11.0 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:

const code = `
import React from 'react'
`
const imports = findImports(
  j(code),
  statement`import { Component } from 'react'`
)

In this case imports would be

{
  Component: {
    type: 'MemberExpression',
    object: {
      type: 'Identifier',
      name: 'React',
    },
    property: {
      type: 'Identifier',
      name: 'Component',
    },
  },
}

Readme

Keywords

Package Sidebar

Install

npm i jscodeshift-find-imports

Weekly Downloads

36,927

Version

2.0.4

License

MIT

Unpacked Size

394 kB

Total Files

6

Last publish

Collaborators

  • jedwards1211