From d239ca6864c0efedc42cd7f2a1b1b98096070143 Mon Sep 17 00:00:00 2001 From: Daniel Del Core Date: Mon, 15 May 2023 17:09:15 +1000 Subject: [PATCH] reference handling insertImportSpec --- .changeset/lazy-crabs-vanish.md | 5 +++++ packages/utils/src/imports.ts | 19 +++++-------------- 2 files changed, 10 insertions(+), 14 deletions(-) create mode 100644 .changeset/lazy-crabs-vanish.md diff --git a/.changeset/lazy-crabs-vanish.md b/.changeset/lazy-crabs-vanish.md new file mode 100644 index 000000000..f94d41fee --- /dev/null +++ b/.changeset/lazy-crabs-vanish.md @@ -0,0 +1,5 @@ +--- +'@codeshift/utils': patch +--- + +InsertImportSpecifier now retains the reference to the original import declaration diff --git a/packages/utils/src/imports.ts b/packages/utils/src/imports.ts index 93344610a..b0ef83246 100644 --- a/packages/utils/src/imports.ts +++ b/packages/utils/src/imports.ts @@ -122,18 +122,9 @@ export function insertImportSpecifier( importSpecifier: ImportSpecifier | ImportDefaultSpecifier, sourcePath: string, ) { - getImportDeclaration(j, source, sourcePath).replaceWith(declaration => - j.importDeclaration( - [ - // we are appending to the existing specifiers - // We are doing a filter hear because sometimes specifiers can be removed - // but they hang around in the declaration - ...(declaration.value.specifiers || []).filter( - item => item.type === 'ImportSpecifier' && item.imported != null, - ), - importSpecifier, - ], - j.literal(sourcePath), - ), - ); + const importDeclaration = getImportDeclaration(j, source, sourcePath); + + if (!importDeclaration) return; + + importDeclaration.get().value.specifiers.push(importSpecifier); }