Skip to content

Commit

Permalink
fix: Parse .ts files without JSX plugin (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon committed Apr 25, 2022
1 parent 9f0f8bc commit c0784a7
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
15 changes: 15 additions & 0 deletions .changeset/tough-dolphins-teach.md
@@ -0,0 +1,15 @@
---
"types-react-codemod": patch
---

Parse .ts files without JSX plugin.

Otherwise code such as

```ts
(<RegExp>expected).test(object);
```

-- https://github.com/DefinitelyTyped/DefinitelyTyped/blob/3eacc5e0b7c56d2670a5a0e68735f7638e8f38f3/types/chai-like/chai-like-tests.ts#L15

could not be parsed.
14 changes: 14 additions & 0 deletions transforms/utils/__tests__/parseSync.js
@@ -0,0 +1,14 @@
import { describe, expect, test } from "@jest/globals";
import parseSync from "../parseSync";

describe("parseSync", () => {
test("oldschool type casts in ts files", () => {
expect(() =>
parseSync({
// based on https://github.com/DefinitelyTyped/DefinitelyTyped/blob/3eacc5e0b7c56d2670a5a0e68735f7638e8f38f3/types/chai-like/chai-like-tests.ts
path: "test.ts",
source: `(<RegExp> expected).test(object);`,
})
).not.toThrow();
});
});
14 changes: 11 additions & 3 deletions transforms/utils/parseSync.js
Expand Up @@ -26,7 +26,6 @@ const baseParserOptions = {
"functionBind",
"functionSent",
"importMeta",
"jsx",
"nullishCoalescingOperator",
"numericSeparator",
"objectRestSpread",
Expand All @@ -41,17 +40,22 @@ const dtsParserOptions = {
...baseParserOptions,
plugins: [...baseParserOptions.plugins, ["typescript", { dts: true }]],
};
const parserOptions = {
const tsParserOptions = {
...baseParserOptions,
plugins: [...baseParserOptions.plugins, ["typescript", { dts: false }]],
};
const tsxParserOptions = {
...tsParserOptions,
plugins: [...tsParserOptions.plugins, "jsx"],
};

/**
* Fork `jscodeshift`'s `tsx` parser with support for .d.ts files
* @param {import('jscodeshift').FileInfo} fileInfo
*/
function parseSync(fileInfo) {
const dts = fileInfo.path.endsWith(".d.ts");
const tsx = fileInfo.path.endsWith(".tsx");

return j(fileInfo.source, {
parser: {
Expand All @@ -69,7 +73,11 @@ function parseSync(fileInfo) {
// So if the parser fails in an ambient context we just try again without ambient context
}
}
return babylon.parse(code, parserOptions);
if (tsx) {
return babylon.parse(code, tsxParserOptions);
} else {
return babylon.parse(code, tsParserOptions);
}
},
},
});
Expand Down

0 comments on commit c0784a7

Please sign in to comment.