Skip to content

Commit f5152b6

Browse files
fix(scoped-jsx): Don't add JSX import if JSX is already imported (#458)
Co-authored-by: Sebastian "Sebbie" Silbermann <[email protected]>
1 parent 96f4328 commit f5152b6

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

.changeset/olive-suns-crash.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"types-react-codemod": patch
3+
---
4+
5+
fix(scoped-jsx): Don't add `JSX` import if `JSX` is already imported

transforms/__tests__/scoped-jsx.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,4 +191,16 @@ describe("transform scoped-jsx", () => {
191191
[].reduce((acc, component, i) => {})"
192192
`);
193193
});
194+
195+
test("existing JSX import from jsx-runtime", () => {
196+
expect(
197+
applyTransform(`
198+
import { JSX } from 'react/jsx-runtime';
199+
declare const element: JSX.Element;
200+
`),
201+
).toMatchInlineSnapshot(`
202+
"import { JSX } from 'react/jsx-runtime';
203+
declare const element: JSX.Element;"
204+
`);
205+
});
194206
});

transforms/scoped-jsx.js

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const traverse = require("@babel/traverse").default;
99
* @param {import('jscodeshift').FileInfo} file
1010
* @param {import('jscodeshift').API} api
1111
*/
12-
const deprecatedReactChildTransform = (file, api) => {
12+
const scopedJsxTransform = (file, api) => {
1313
const j = api.jscodeshift;
1414
const ast = parseSync(file);
1515

@@ -34,7 +34,7 @@ const deprecatedReactChildTransform = (file, api) => {
3434
},
3535
});
3636

37-
if (hasGlobalNamespaceReferences) {
37+
if (hasGlobalNamespaceReferences && !isJsxAlreadyImported(j, ast)) {
3838
const reactImport = findReactImportForNewImports(j, ast);
3939
const jsxImportSpecifier = reactImport.find(j.ImportSpecifier, {
4040
imported: { name: "JSX" },
@@ -73,4 +73,16 @@ const deprecatedReactChildTransform = (file, api) => {
7373
return file.source;
7474
};
7575

76-
module.exports = deprecatedReactChildTransform;
76+
/**
77+
* @param {import('jscodeshift').API['jscodeshift']} j
78+
* @param {import('jscodeshift').Collection} ast
79+
*/
80+
function isJsxAlreadyImported(j, ast) {
81+
return (
82+
ast.find(j.ImportSpecifier, {
83+
local: { name: "JSX" },
84+
}).length > 0
85+
);
86+
}
87+
88+
module.exports = scopedJsxTransform;

0 commit comments

Comments
 (0)