Skip to content

Commit

Permalink
fix(scoped-jsx): Don't add JSX import if JSX is already imported (#…
Browse files Browse the repository at this point in the history
…458)

Co-authored-by: Sebastian "Sebbie" Silbermann <[email protected]>
  • Loading branch information
henryqdineen and eps1lon authored Dec 16, 2024
1 parent 96f4328 commit f5152b6
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/olive-suns-crash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"types-react-codemod": patch
---

fix(scoped-jsx): Don't add `JSX` import if `JSX` is already imported
12 changes: 12 additions & 0 deletions transforms/__tests__/scoped-jsx.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,16 @@ describe("transform scoped-jsx", () => {
[].reduce((acc, component, i) => {})"
`);
});

test("existing JSX import from jsx-runtime", () => {
expect(
applyTransform(`
import { JSX } from 'react/jsx-runtime';
declare const element: JSX.Element;
`),
).toMatchInlineSnapshot(`
"import { JSX } from 'react/jsx-runtime';
declare const element: JSX.Element;"
`);
});
});
18 changes: 15 additions & 3 deletions transforms/scoped-jsx.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const traverse = require("@babel/traverse").default;
* @param {import('jscodeshift').FileInfo} file
* @param {import('jscodeshift').API} api
*/
const deprecatedReactChildTransform = (file, api) => {
const scopedJsxTransform = (file, api) => {
const j = api.jscodeshift;
const ast = parseSync(file);

Expand All @@ -34,7 +34,7 @@ const deprecatedReactChildTransform = (file, api) => {
},
});

if (hasGlobalNamespaceReferences) {
if (hasGlobalNamespaceReferences && !isJsxAlreadyImported(j, ast)) {
const reactImport = findReactImportForNewImports(j, ast);
const jsxImportSpecifier = reactImport.find(j.ImportSpecifier, {
imported: { name: "JSX" },
Expand Down Expand Up @@ -73,4 +73,16 @@ const deprecatedReactChildTransform = (file, api) => {
return file.source;
};

module.exports = deprecatedReactChildTransform;
/**
* @param {import('jscodeshift').API['jscodeshift']} j
* @param {import('jscodeshift').Collection} ast
*/
function isJsxAlreadyImported(j, ast) {
return (
ast.find(j.ImportSpecifier, {
local: { name: "JSX" },
}).length > 0
);
}

module.exports = scopedJsxTransform;

0 comments on commit f5152b6

Please sign in to comment.