Skip to content

Commit b9a28ab

Browse files
author
Daniel Del Core
committed
avoids inserting an import specifier if it already exists
1 parent 760aa23 commit b9a28ab

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

.changeset/mighty-rules-drop.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@codeshift/utils': patch
3+
---
4+
5+
insertImportSpecifier no longer adds duplicate entries if it already exists

packages/utils/src/imports.spec.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,26 @@ describe('imports', () => {
4141
expect(result).toMatchInlineSnapshot(`"import { bar } from 'bar';"`);
4242
});
4343

44+
it('does not insert an import specifier if already exists', async () => {
45+
const transform = (file: FileInfo, api: API) => {
46+
const j = api.jscodeshift;
47+
const source = j(file.source);
48+
importUtils.insertImportSpecifier(
49+
j,
50+
source,
51+
j.importSpecifier(j.identifier('bar')),
52+
'bar',
53+
);
54+
55+
return source.toSource();
56+
};
57+
const result = await applyTransform(
58+
transform,
59+
`import { bar } from 'bar';`,
60+
);
61+
expect(result).toMatchInlineSnapshot(`"import { bar } from 'bar';"`);
62+
});
63+
4464
it('maintains a reference to importDec and is able to inserts import specifier', async () => {
4565
const transform = (file: FileInfo, api: API) => {
4666
const j = api.jscodeshift;

packages/utils/src/imports.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,14 +119,21 @@ export function hasImportSpecifier(
119119
export function insertImportSpecifier(
120120
j: core.JSCodeshift,
121121
source: Collection<any>,
122-
importSpecifier: ImportSpecifier | ImportDefaultSpecifier,
122+
specifier: ImportSpecifier | ImportDefaultSpecifier,
123123
sourcePath: string,
124124
) {
125125
const importDeclaration = getImportDeclaration(j, source, sourcePath);
126126

127127
if (!importDeclaration) return;
128128

129-
importDeclaration.get().value.specifiers.push(importSpecifier);
129+
if (
130+
specifier.type === 'ImportSpecifier' &&
131+
hasImportSpecifier(j, source, specifier.imported.name, sourcePath)
132+
) {
133+
return;
134+
}
135+
136+
importDeclaration.get().value.specifiers.push(specifier);
130137
}
131138

132139
export function removeImportSpecifier(

0 commit comments

Comments
 (0)