The convention I want to use in the codebase is:
const a = 1;
const b = 2;
However, there are many areas in the code that are written like this:
let a = 1,
b = 2;
I want to write a codemod, probably using JSCodeshift that can change the second style of variable declaration to the first. I have been doing some research on ASTs and have been using AST explorer. However, I am having trouble accessing the variable declarator "kind" in the abstract syntax tree.
An example of something I've tried is this:
module.exports = function(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
// Step 1: Find all instances of the code to change
const instances = root.find(VariableDeclarator.value.kind = 'let');
// Step 2: Apply a code transformation and replace the code
instances.forEach(instance => {
j(path).replaceWith(VariableDeclarator.value.kind = 'const');
});
return root.toSource();
}
}
Any help or direction would be appreciated! Thank you!
You can use
Putout
code transformer, I’m working on, with@putout/plugin-split-variable-declarations
this way:Here is example from
Putout Editor
: