'Codemod vs. eslint --fix

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?



Solution 1:[1]

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:

  1. 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.

  2. 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.

Solution 2:[2]

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:

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:

Putout Editor

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2