Codemod2.0
This guide shows how you can build, test, and publish a Codemod 2.0 in a few steps. In the following example, we consider a use case where we want to create a codemod to change imports to direct imports:
Step 1: Initialize a new codemod.
Run npx codemod@latest init
in your desired location to store the codemod folder, and select workflow
as your engine. This sets up the scaffolding for your codemod, making it easy to provide configuration and metadata. While optional for building and running a codemod, this step enhances discoverability and sharing.
Step 2: Find JS/TS files.
From the previous step, we got a new directory mui-named-import-to-direct-import
and file inside src/index.ts
. Let’s update this boilerplate file.
We need to get all the files that potentially can have Material UI Icons imports
Now let’s get Javascript/Typescript context:
Step 3: Use ast-grep for pattern detection.
Let’s use ast-grep which is built-in into our workflow engine
ast-grep allows matching code with a … code. $$$_
pattern means any number of elements, in our case any number of named imports.
Step 4: Use AI for code transformation.
Now that we have all the needed files and imports, we should fix it somehow. We can write some logic to handle different cases, like support of aliases or … we can just ask LLM to make changes
Step 5: Run and test the codemod locally.
Let’s check it out:
And here is our fixed file:
Step 6: Publish the Codemod
Now that our codemod is ready, we can publish it to Codemod Registry. This allows your codemod to be:
- easily accessible to the open source community and your peers
- seamlessly distributed upon releasing new versions
- integrated with the rest of Codemod platform
Now that the codemod is published, you can easily run it from Codemode Registry:
P.S.
If you want simplify things more, take a look at workflow engine documentation and improve code a little bit:
Was this page helpful?