https://github.com/codemodsquad/jscodeshift-add-imports
add imports/requires if not already present with jscodeshift
https://github.com/codemodsquad/jscodeshift-add-imports
codemods imports jscodeshift refactoring
Last synced: 2 months ago
JSON representation
add imports/requires if not already present with jscodeshift
- Host: GitHub
- URL: https://github.com/codemodsquad/jscodeshift-add-imports
- Owner: codemodsquad
- License: mit
- Created: 2019-05-22T17:07:55.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2024-07-19T16:40:34.000Z (about 1 year ago)
- Last Synced: 2025-07-28T09:45:54.132Z (2 months ago)
- Topics: codemods, imports, jscodeshift, refactoring
- Language: JavaScript
- Size: 1.38 MB
- Stars: 26
- Watchers: 1
- Forks: 4
- Open Issues: 23
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# jscodeshift-add-imports
[](https://circleci.com/gh/codemodsquad/jscodeshift-add-imports)
[](https://codecov.io/gh/codemodsquad/jscodeshift-add-imports)
[](https://github.com/semantic-release/semantic-release)
[](http://commitizen.github.io/cz-cli/)
[](https://badge.fury.io/js/jscodeshift-add-imports)Easily add import and require statements with jscodeshift. If something is already
imported, returns the locally bound identifier, and avoids name conflicts.# Usage
```
npm install --save jscodeshift-add-imports
``````js
const j = require('jscodeshift')
const addImports = require('jscodeshift-add-imports')const { statement } = j.template
const code = `
// @flow
import {foo, type bar} from 'foo'
import baz from 'baz'
`const root = j(code)
const result = addImports(root, [
statement`import type {bar, baz} from 'foo'`,
statement`import blah, {type qux} from 'qux'`,
])
console.log(result)
console.log(root.toSource())
```Output code:
```js
// @flow
import { foo, type bar } from 'foo'
import baz from 'baz'
import type { baz as baz1 } from 'foo'
import blah, { type qux } from 'qux'
```Return value:
```js
{
bar: 'bar',
baz: 'baz1',
blah: 'blah',
qux: 'qux',
}
```# Compatibility
Currently tested on `jscodeshift@0.11.0` with the following parsers:
- `babylon`
- `ts`There are currently issues with the `babel` and `flow` parsers.
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.# `addImports(root, statments)`
## Arguments
### `root`
The jscodeshift-wrapped AST of your source code
### `statements`
The AST of an import declaration or variable declaration with requires to add,
or an array of them.## Return value
An object where the key is the local identifier you requested in `statements`,
and the value is the resulting local identifier used in the modified
code (which could be the existing local identifier already imported in the code or
the local identifier chosen to avoid name conflicts with an existing binding)