Parameterized Codemods
Create codemods that accept arguments that tailor its behavior to specific needs.
Writing parameterized codemods is a powerful technique to create flexible and reusable transformations that can be applied to a wide range of codebases. Parameterized codemods accept arguments or options that customize their behavior, allowing them to adapt to different coding styles, project structures, or specific refactoring needs. This guide will cover the basics of writing parameterized codemods, the benefits of using them, and provide an example to illustrate the concept.
How to define parameters
To write a parameterized codemod, you'll typically use a library like jscodeshift and leverage Hypermod for additional utilities and ease of authoring. Here's a basic template for a parameterized codemod:
export default function transformer(file, api, options) {
const j = api.jscodeshift;
const root = j(file.source);
// Access custom parameters from options
const customParameter = options.customParameter || 'default';
// Use the parameter in your transformation logic
root.find(j.Identifier).forEach((path) => {
if (path.node.name === customParameter) {
// Perform some transformation
}
});
return root.toSource();
}
In this example, customParameter
is a parameter that can be passed to the codemod to customize its behavior, such as specifying a variable name to target for renaming.
Providing parameters at run-time
To run a parameterized codemod with @hypermod/cli, you can pass options via the command line:
npx @hypermod/cli -t path/to/your/codemod.js --customParameter="myVariable" path/to/source/files
This command runs the codemod located at path/to/your/codemod.js
on the files in path/to/source/files
, passing myVariable
as the value for customParameter
.
Example: Renaming a Variable
Let's say you want to create a codemod that renames a variable across your project. The variable name to be replaced and the new name can be passed as parameters:
export default function transformer(file, api, options) {
const j = api.jscodeshift;
// Variables to be renamed are passed as options
const oldName = options.oldName;
const newName = options.newName;
j(file.source)
.find(j.Identifier, { name: oldName })
.replaceWith(j.identifier(newName));
return root.toSource({ quote: 'single' });
}
To run this codemod and rename oldVariableName
to newVariableName
, you would execute:
npx @hypermod/cli -t path/to/your/variableRenameCodemod.js path/to/source/files --oldName="oldVariableName" --newName="newVariableName"
Parameterized codemods offer a powerful and flexible approach to code transformations, making them an invaluable tool for developers looking to efficiently refactor and maintain their codebases. By leveraging parameters, you can create adaptable and reusable codemods that meet a variety of refactoring needs.