Skip to content
This repository has been archived by the owner on Feb 16, 2024. It is now read-only.

Commit

Permalink
fix imports copied twice (#360)
Browse files Browse the repository at this point in the history
* fix imports copied twice

* fix test
  • Loading branch information
DmytroHryshyn authored Sep 21, 2023
1 parent 28af725 commit 8266571
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 8 deletions.
16 changes: 8 additions & 8 deletions next/13/replace-next-head/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1622,17 +1622,17 @@ const mergeOrCreateImports = (

const importedModule =
importDeclarations.find((importDeclaration) => {
const oldSpecifierText = importDeclaration
const oldPathRelative = importDeclaration
.getModuleSpecifier()
.getText();
.getLiteralText();

// compare by absolute paths
const oldPath = resolveModuleName(
oldSpecifierText.substring(1, oldSpecifierText.length - 1),
path,
);
const oldPathAbsolute = resolveModuleName(oldPathRelative, path);

return oldPath === moduleSpecifier;
const moduleIsLibOrUnresolved = oldPathAbsolute === null;
return (
oldPathAbsolute === moduleSpecifier ||
(moduleIsLibOrUnresolved && oldPathRelative === moduleSpecifier)
);
}) ?? null;

const pathIsAbsolute = isAbsolute(moduleSpecifier);
Expand Down
51 changes: 51 additions & 0 deletions next/13/replace-next-head/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,57 @@ Checkout my React component:
);
});

it('should move identifier definitions that are ImportDeclarations: should not copy dependencies multiple times ', async function (this: Context) {
const A_CONTENT = `
import Head from 'next/head';
import A from 'lib';
export default function Page() {
return (<>
<Head>
<meta property="og:image" content={A} />
<meta property="twitter:image" content={A} />
</Head>
</>)
}
`;

const [command] = await transform({
'/opt/project/pages/a/index.tsx': A_CONTENT,
});

const expectedResult = `
import { Metadata } from "next";
import Head from 'next/head';
import A from 'lib';
export const metadata: Metadata = {
openGraph: {
images: [{
url: A
}]
}
}
export default function Page() {
return (<>
<Head>
<meta property="og:image" content={A} />
<meta property="twitter:image" content={A} />
</Head>
</>)
}
`;

deepStrictEqual(command?.kind, 'upsertFile');
deepStrictEqual(command.path, '/opt/project/pages/a/index.tsx');

deepStrictEqual(
command.data.replace(/\s/gm, ''),
expectedResult.replace(/\s/gm, ''),
);
});

it('should move identifier definitions that are ImportDeclarations: should not update moduleSpecifier if moving a library ', async function (this: Context) {
const A_CONTENT = `
import Meta from '../../components/a.tsx';
Expand Down

0 comments on commit 8266571

Please sign in to comment.