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(Codemod) : Preact Migrations vX #1262

Open
wants to merge 5 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
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",
"name": "preact/X/default-import-to-namespace-import",
"version": "1.0.0",
"engine": "jscodeshift",
"private": false,
"arguments": [],
"meta": {
"tags": ["preact", "migration"],
"git": "https://github.com/codemod-com/codemod/tree/main/packages/codemods/preact/X/default-import-to-namespace-import"
},
"applicability": {
"from": [["preact", "<", "8.x"]]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2024 Codemod Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
A codemod that converts named imports of Preact to namespace imports for improved compatibility and consistency.

### Before

```ts
import Preact from 'preact';
```

### After

```ts
import * as preact from 'preact';
```

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import Preact from 'preact';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import * as preact from 'preact';
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "preact-convert-default-import-to-namespace-import",
"license": "MIT",
"devDependencies": {
"@types/node": "20.9.0",
"typescript": "^5.2.2",
"vitest": "^1.0.1",
"@codemod.com/codemod-utils": "*",
"jscodeshift": "^0.15.1",
"@types/jscodeshift": "^0.11.10"
},
"scripts": {
"test": "vitest run",
"test:watch": "vitest watch"
},
"files": ["README.md", ".codemodrc.json", "/dist/index.cjs"],
"type": "module",
"author": "manishjha-04"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export default function transformer(fileInfo, api) {
const j = api.jscodeshift;
const root = j(fileInfo.source);

// Find all import declarations from 'preact'
root
.find(j.ImportDeclaration, { source: { value: "preact" } })
.forEach((path) => {
// Check if the import is a default import
const defaultImportSpecifier = path.node.specifiers.find(
(specifier) => specifier.type === "ImportDefaultSpecifier",
);

if (defaultImportSpecifier) {
// Replace the default import with a namespace import
path.node.specifiers = [
j.importNamespaceSpecifier(j.identifier("preact")),
];
}
});

return root.toSource();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
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("preact/convert-default-import-to-namespace-import", () => {
it("test #1", async () => {
const INPUT = await readFile(
join(__dirname, "..", "__testfixtures__/fixture1.input.ts"),
"utf-8",
);
const OUTPUT = await readFile(
join(__dirname, "..", "__testfixtures__/fixture1.output.ts"),
"utf-8",
);

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

assert.deepEqual(
actualOutput?.replace(/W/gm, ""),
OUTPUT.replace(/W/gm, ""),
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"compilerOptions": {
"module": "NodeNext",
"target": "ESNext",
"moduleResolution": "NodeNext",
"lib": ["ESNext", "DOM"],
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"jsx": "react-jsx",
"useDefineForClassFields": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"preserveWatchOutput": true,
"strict": true,
"strictNullChecks": true,
"incremental": true,
"noUncheckedIndexedAccess": true,
"noPropertyAccessFromIndexSignature": false,
"allowJs": true
},
"include": [
"./src/**/*.ts",
"./src/**/*.js",
"./test/**/*.ts",
"./test/**/*.js"
],
"exclude": ["node_modules", "./dist/**/*"],
"ts-node": {
"transpileOnly": true
}
}
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"],
},
});
15 changes: 15 additions & 0 deletions packages/codemods/preact/X/import-source-update/.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",
"name": "preact/X/preact-import-source-update",
"version": "1.0.0",
"engine": "jscodeshift",
"private": false,
"arguments": [],
"meta": {
"tags": ["preact", "X", "migration"],
"git": "https://github.com/codemod-com/codemod/tree/main/packages/codemods/preact/X/import-source-update"
},
"applicability": {
"from": [["preact", "<", "8.x"]]
}
}
2 changes: 2 additions & 0 deletions packages/codemods/preact/X/import-source-update/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
9 changes: 9 additions & 0 deletions packages/codemods/preact/X/import-source-update/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2024 Codemod Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 changes: 23 additions & 0 deletions packages/codemods/preact/X/import-source-update/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
A codemod that updates imports from Preact to React equivalents and modifies certain Preact imports for compatibility.

**Detailed description:**
This codemod refactors imports in your codebase to align with React or modern Preact practices. It changes `preact-redux` imports to `react-redux`, updates `mobx-preact` to `mobx-react`, and ensures that Preact compatibility imports are correctly handled by switching to `preact/compat`.

## Example

### Before

```ts
import { Provider } from 'preact-redux';
import { observer } from 'mobx-preact';
import { render } from 'preact-compat';
```

### After

```ts
import { Provider } from 'react-redux';
import { observer } from 'mobx-react';
import { createPortal } from 'preact/compat';
import { render } from 'preact/compat';
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { Provider } from 'preact-redux';
import { observer } from 'mobx-preact';
import { render } from 'preact-compat';
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { Provider } from "react-redux";
import { observer } from "mobx-react";
import { createPortal } from "preact/compat";
import { render } from "preact/compat";
19 changes: 19 additions & 0 deletions packages/codemods/preact/X/import-source-update/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "preact-10-import-source-update",
"license": "MIT",
"devDependencies": {
"@types/node": "20.9.0",
"typescript": "^5.2.2",
"vitest": "^1.0.1",
"@codemod.com/codemod-utils": "*",
"jscodeshift": "^0.15.1",
"@types/jscodeshift": "^0.11.10"
},
"scripts": {
"test": "vitest run",
"test:watch": "vitest watch"
},
"files": ["README.md", ".codemodrc.json", "/dist/index.cjs"],
"type": "module",
"author": "manishjha-04"
}
25 changes: 25 additions & 0 deletions packages/codemods/preact/X/import-source-update/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export default function transform(fileInfo, api) {
const j = api.jscodeshift;

return j(fileInfo.source)
.find(j.ImportDeclaration)
.forEach((path) => {
const importSource = path.node.source.value;

// Update imports from 'preact-compat' to 'preact/compat'
if (importSource === "preact-compat") {
path.node.source.value = "preact/compat";
}

// Update imports from 'preact-redux' to 'react-redux'
if (importSource === "preact-redux") {
path.node.source.value = "react-redux";
}

// Update imports from 'mobx-preact' to 'mobx-react'
if (importSource === "mobx-preact") {
path.node.source.value = "mobx-react";
}
})
.toSource();
}
48 changes: 48 additions & 0 deletions packages/codemods/preact/X/import-source-update/test/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
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("preact/10/import-source-update", () => {
it("test #1", async () => {
const INPUT = await readFile(
join(__dirname, "..", "__testfixtures__/fixture1.input.ts"),
"utf-8",
);
const OUTPUT = await readFile(
join(__dirname, "..", "__testfixtures__/fixture1.output.ts"),
"utf-8",
);

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

assert.deepEqual(

Check failure on line 43 in packages/codemods/preact/X/import-source-update/test/test.ts

View workflow job for this annotation

GitHub Actions / Run unit tests (ubuntu-latest, true)

packages/codemods/preact/X/import-source-update/test/test.ts > preact/10/import-source-update > test #1

AssertionError: Expected values to be loosely deep-equal: 'import { Provider } from "react-redux";\n' + 'import { observer } from "mobx-react";\n' + 'import { render } from "preact/compat";' should loosely deep-equal 'import { Provider } from "react-redux";\n' + 'import { observer } from "mobx-react";\n' + 'import { createPortal } from "preact/compat";\n' + 'import { render } from "preact/compat";' - Expected + Received import { Provider } from "react-redux"; import { observer } from "mobx-react"; - import { createPortal } from "preact/compat"; import { render } from "preact/compat"; ❯ packages/codemods/preact/X/import-source-update/test/test.ts:43:12
actualOutput?.replace(/W/gm, ""),
OUTPUT.replace(/W/gm, ""),
);
});
});
35 changes: 35 additions & 0 deletions packages/codemods/preact/X/import-source-update/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"compilerOptions": {
"module": "NodeNext",
"target": "ESNext",
"moduleResolution": "NodeNext",
"lib": ["ESNext", "DOM"],
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"jsx": "react-jsx",
"useDefineForClassFields": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"preserveWatchOutput": true,
"strict": true,
"strictNullChecks": true,
"incremental": true,
"noUncheckedIndexedAccess": true,
"noPropertyAccessFromIndexSignature": false,
"allowJs": true
},
"include": [
"./src/**/*.ts",
"./src/**/*.js",
"./test/**/*.ts",
"./test/**/*.js"
],
"exclude": ["node_modules", "./dist/**/*"],
"ts-node": {
"transpileOnly": true
}
}
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"],
},
});
Loading
Loading