I want to write a couple of scripts to automatically detect missing imports and import them based upon a root directory. Is it better to write this script as a codemod script or as an eslint rule with the fix option?
Codemod vs. eslint --fix
544 views Asked by Josh Unger At
2
There are 2 answers
2
On
You can combine both worlds and use Putout code transformer I’m working on for a couple years. It can be used as a plugin for ESLint and very useful for writing codemods
, because it has all needed infrastructure:
- ✅ test runner;
- ✅ declarative API based on templates;
- ✅ handbook to learn from;
- ✅ an editor;
With help of scopes you can easily detect is variable that you use is declared or not.
Here is example of a plugin
which does what you need: @putout/plugin-declare-undefined-variables it works this way:
import {template} from 'putout';
export const match = () => ({
'await readFile(__a, __b)': (vars, path) => {
return !path.scope.bindings.readFile;
}
});
export const replace = () => ({
'await readFile(__a, __b)': (vars, path) => {
const programScope = path.scope.getProgramParent();
const importNode = template.ast('import {readFile} from "fs/promises"');
programScope.path.node.body.unshift(importNode);
return path;
}
});
Here is how it looks like in Putout Editor:
Codemods are meant for migrations while linting is there permanently to nag/warn your developers about some mistake they have potentially made while developing. Both can be used together.
For your case, I think there are two approaches you can take:
Write a lint rule that detects the problem and a codemod to fix existing occurences of the problem. The lint rule ensures that developers won't miss that out in future.
Write a lint rule that detects the problem along with a
--fix
option to automatically fix the problem.I would lean towards approach two because it's more futureproof. You might want to just use this
no-unresolved
ESLint rule directly rather than writing your own. In any case, the fix/codemod is not trivial and can be a performance hit if your project has many directories and files.