Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: react v19 codemods #1

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,9 @@ workflows:
- "-r=www-modern --env=development --variant=true"
- "-r=www-modern --env=production --variant=true"

# Codemods
- "--project=codemods -r=experimental"

# TODO: Test more persistent configurations?
- '-r=stable --env=development --persistent'
- '-r=experimental --env=development --persistent'
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.DS_STORE
dist
node_modules
scripts/flow/*/.flowconfig
.flowconfig
Expand Down
4 changes: 4 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
'use strict';

module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
],
plugins: [
'@babel/plugin-syntax-jsx',
'@babel/plugin-transform-flow-strip-types',
Expand Down
15 changes: 15 additions & 0 deletions codemods/ref-to-arrow-function-ref/.codemodrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://codemod-utils.s3.us-west-1.amazonaws.com/configuration_schema.json",
"version": "1.0.3",
"private": false,
"name": "react/19/ref-to-arrow-function",
"engine": "jscodeshift",
"meta": {
"tags": ["react", "migration"],
"git": "https://github.com/codemod-com/react/tree/codemods-v19/codemods/ref-to-arrow-function-ref"
},
"applicability": {
"from": [["react", "<=", "18"]],
"to": [["react", "=", "19"]]
}
}
14 changes: 14 additions & 0 deletions codemods/ref-to-arrow-function-ref/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
This codemod migrates string refs (deprecated) to callback refs.

## Before

```ts
< div ref = 'refName' / > ;
```

## After

```ts
< div ref = { ref => this.refs.refName = ref }
/>
```
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<div ref="refName" />;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<div
ref={(ref) => {
this.refs.refName = ref;
}}
/>;
47 changes: 47 additions & 0 deletions codemods/ref-to-arrow-function-ref/__tests__/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import assert from "node:assert";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import jscodeshift, { type API } from "jscodeshift";
import { describe, it } from "vitest";
import transform from "../src/index.js";

const buildApi = (parser: string | undefined): API => ({
j: parser ? jscodeshift.withParser(parser) : jscodeshift,
jscodeshift: parser ? jscodeshift.withParser(parser) : jscodeshift,
stats: () => {
console.error(
"The stats function was called, which is not supported on purpose",
);
},
report: () => {
console.error(
"The report function was called, which is not supported on purpose",
);
},
});

describe("react/19/ref-to-arrow-function", () => {
it("test #1", async () => {
const INPUT = await readFile(
join(__dirname, "..", "__testfixtures__/fixture1.input.tsx"),
"utf-8",
);
const OUTPUT = await readFile(
join(__dirname, "..", "__testfixtures__/fixture1.output.tsx"),
"utf-8",
);

const actualOutput = transform(
{
path: "index.js",
source: INPUT,
},
buildApi("tsx"),
);

assert.deepEqual(
actualOutput?.replace(/\s/gm, ""),
OUTPUT.replace(/\s/gm, ""),
);
});
});
19 changes: 19 additions & 0 deletions codemods/ref-to-arrow-function-ref/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "ref-to-arrow-function",
"author": "codemod",
"dependencies": {},
"devDependencies": {
"@types/node": "20.9.0",
"typescript": "5.2.2",
"vitest": "^1.0.1",
"jscodeshift": "^0.15.1",
"@types/jscodeshift": "^0.11.10"
},
"scripts": {
"test": "vitest run",
"test:watch": "vitest watch"
},
"license": "MIT",
"files": ["README.md", ".codemodrc.json", "./dist/index.cjs"],
"type": "module"
}
81 changes: 81 additions & 0 deletions codemods/ref-to-arrow-function-ref/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import type { API, FileInfo, Options } from "jscodeshift";
export default function transform(
file: FileInfo,
api: API,
options?: Options,
): string | undefined {
const j = api.jscodeshift;
const root = j(file.source);

// Helper function to preserve comments
function replaceWithComments(path, newNode) {
// If the original node had comments, add them to the new node
if (path.node.comments) {
newNode.comments = path.node.comments;
}

// Replace the node
j(path).replaceWith(newNode);
}

// Find JSX elements with ref attribute
root
// Find JSX elements with a ref attribute
.find(j.JSXElement)
.forEach((path) => {
// Get the ref name
const refName = path.node.openingElement.attributes.find(
(attr) => attr?.name?.name === "ref",
)?.value?.value;

if (typeof refName !== "string") {
return;
}

// Create new ref attribute
const newRefAttr = j.jsxAttribute(
j.jsxIdentifier("ref"),
j.jsxExpressionContainer(
j.arrowFunctionExpression(
[j.jsxIdentifier("ref")],
j.blockStatement([
j.expressionStatement(
j.assignmentExpression(
"=",
j.memberExpression(
j.memberExpression(
j.thisExpression(),
j.identifier("refs"),
),
j.identifier(refName),
),
j.identifier("ref"),
),
),
]),
),
),
);

// Replace old ref attribute with new one
const newAttributes = path.node.openingElement.attributes.map((attr) =>
attr?.name?.name === "ref" ? newRefAttr : attr,
);
const newOpeningElement = j.jsxOpeningElement(
path.node.openingElement.name,
newAttributes,
path.node.openingElement.selfClosing,
);
const newElement = j.jsxElement(
newOpeningElement,
path.node.closingElement,
path.node.children,
path.node.selfClosing,
);

// Replace old element with new one, preserving comments
replaceWithComments(path, newElement);
});

return root.toSource();
}
23 changes: 23 additions & 0 deletions codemods/ref-to-arrow-function-ref/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"module": "NodeNext",
"skipLibCheck": true,
"strict": true,
"target": "ES6",
"allowJs": true
},
"include": [
"./src/**/*.ts",
"./src/**/*.js",
"./test/**/*.ts",
"./test/**/*.js"
],
"exclude": ["node_modules", "./dist/**/*"],
"ts-node": {
"transpileOnly": true
}
}
7 changes: 7 additions & 0 deletions codemods/ref-to-arrow-function-ref/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { configDefaults, defineConfig } from "vitest/config";

export default defineConfig({
test: {
include: [...configDefaults.include, "**/test/*.ts"],
},
});
12 changes: 12 additions & 0 deletions codemods/remove-context-provider/.codemodrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"version": "1.0.0",
"name": "react/19/remove-context-provider",
"private": false,
"engine": "jscodeshift",
"meta": {
"tags": ["react", "migration"]
},
"applicability": {
"from": [["react", "<=", "^18.0.0"]]
r4zendev marked this conversation as resolved.
Show resolved Hide resolved
}
}
35 changes: 35 additions & 0 deletions codemods/remove-context-provider/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Change Context.Provider to Context

## Description

This codemod will remove the usage of `Provider` for contexts; e.g., Context.Provider to Context

## Example

### Before:

```tsx
function App() {
const [theme, setTheme] = useState('light');
// ...
return (
<ThemeContext.Provider value={theme}>
<Page />
</ThemeContext.Provider>
);
}
```

### After:

```tsx
function App() {
const [theme, setTheme] = useState('light');
// ...
return (
<ThemeContext value={theme}>
<Page />
</ThemeContext>
);
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function App() {
const [theme, setTheme] = useState('light');

return (
<ThemeContext.Provider value={theme}>
<Page />
</ThemeContext.Provider>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function App() {
const [theme, setTheme] = useState('light');

return (
<ThemeContext value={theme}>
<Page />
</ThemeContext>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function App() {
const [theme, setTheme] = useState('light');

return (
<Context.Provider value={theme}>
<Page />
</Context.Provider>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function App() {
const [theme, setTheme] = useState('light');

return (
<Context value={theme}>
<Page />
</Context>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function App() {
const [theme, setTheme] = useState('light');

return (
<Context value={theme}>
<Page />
</Context>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function App() {
const [theme, setTheme] = useState('light');

return (
<Context value={theme}>
<Page />
</Context>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function App({ url }: { url: string }) {
const [theme, setTheme] = useState<'light' | 'dark'>('light');

return (
<ThemeContext.Provider value={theme}>
<Page />
</ThemeContext.Provider>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function App({ url }: { url: string }) {
const [theme, setTheme] = useState<'light' | 'dark'>('light');

return (
<ThemeContext value={theme}>
<Page />
</ThemeContext>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function App({ url }: { url: string }) {
const [theme, setTheme] = useState<'light' | 'dark'>('light');

return (
<Context.Provider value={theme}>
<Page />
</Context.Provider>
);
}
Loading