How to run "Convert 'require' to 'import'" with ts-morph

135 views Asked by At

Im trying to covert 'require' to 'import' programatically. I see that vs-code have such feature builtin.

enter image description here

Currenlty im using ts-morph Also i found such repo https://github.com/typescript-language-server/typescript-language-server

but there is not good example on how to run Apply Code Action via API

https://github.com/typescript-language-server/typescript-language-server

1

There are 1 answers

0
Dmitrio On

I cannot attest to doing what you need using typescript-language-server but you can do this using a jscodeshift codemod. This should work similar to how a ts-morph codemod works. This codemod should help you convert require to import as needed:

import type { FileInfo, API, Options } from 'jscodeshift';
export default function transform(
    file: FileInfo,
    api: API,
    options: Options,
): string | undefined {
    const j = api.jscodeshift;
    const root = j(file.source);

    // Find all require calls
    root.find(j.CallExpression, {
        callee: { type: 'Identifier', name: 'require' },
    }).forEach((path) => {
        // Ensure the parent node is a VariableDeclarator
        if (path.parent.node.type === 'VariableDeclarator') {
            // Get the variable name
            const varName = path.parent.node.id.name;
            // Get the module name
            const moduleName = path.node.arguments[0].value;
            // Replace the parent (VariableDeclaration) with an ImportDeclaration
            j(path.parent.parent).replaceWith(
                j.importDeclaration(
                    [j.importDefaultSpecifier(j.identifier(varName))],
                    j.literal(moduleName),
                ),
            );
        }
    });

    return root.toSource();
}

It seems that you are having issues with running the codemod as well. You simply have to follow the usage guidelines of jscodeshift CLI. In this case, you can simply place the codemod in a .js file and run the following command:

jscodeshift -t some-transform.js input-file.js -d -p

The -d flag runs the codemod in dry-run mode. You can omit this if you want the project files to be affected. The -p flag prints out the codemod run results. It's recommended that you keep this especially when testing out the codemod. input-file.js can be replaced with the path that should be affected by the codemod. You can limit the codemod run to specific directories or files within the project.