Skip to content

Commit 3d0d831

Browse files
committed
✨ Adds renameImportDeclaration util
1 parent a9eae1d commit 3d0d831

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

packages/utils/src/imports.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,18 @@ export function removeImportDeclaration(
3232
getImportDeclaration(j, source, sourcePath).remove();
3333
}
3434

35+
export function renameImportDeclaration(
36+
j: core.JSCodeshift,
37+
source: Collection<any>,
38+
sourcePath: string,
39+
newSourcePath: string,
40+
) {
41+
getImportDeclaration(j, source, sourcePath).forEach(
42+
importDeclaration =>
43+
(importDeclaration.node.source = j.stringLiteral(newSourcePath)),
44+
);
45+
}
46+
3547
export function getDefaultImportSpecifier(
3648
j: core.JSCodeshift,
3749
source: Collection<any>,

website/docs/api/codeshift-utils.mdx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,33 @@ removeImportDeclaration(j, source, 'react');
8585
-import React, { useEffect } from 'react';
8686
```
8787

88+
### `renameImportDeclaration(j, source, sourcePath, newSourcePath)`
89+
90+
Renames an import declaration by source name
91+
92+
**Returns**
93+
94+
`void`
95+
96+
**Example**
97+
98+
```jsx
99+
// src/App.js
100+
import React from 'react';
101+
```
102+
103+
```js
104+
import { renameImportDeclaration } from '@codeshift/utils';
105+
106+
renameImportDeclaration(j, source, 'react', 'preact');
107+
```
108+
109+
```diff
110+
// src/App.js
111+
-import React, { useEffect } from 'react';
112+
+import React, { useEffect } from 'preact';
113+
```
114+
88115
### `getDefaultImportSpecifier(j, source, sourcePath)`
89116

90117
Finds a default import specifier

0 commit comments

Comments
 (0)