Skip to content

using ast-grep for codemod #10

@hyesungoh

Description

@hyesungoh

after merged #9 (because reliable test case are there)

We can consider using ast-grep for better performance and readable code (I think 🤔

benchmarks

I deployed poc packages

ast-grep based is hyesungoh-poc-ast-grep
jscodeshift based is hyesungoh-test-codemod

ast-grep based at jest-dom

Image

jscodeshift based at jest-dom

Image

ast-grep based at react/fixtures

Image

jscodeshift based at react/fixtures

Image

conclusion

I believe that in most cases, the ast-grep-based system performs better.

coinclusion with downloads time

The difference in unpacked size between the two packages is only 3.42KB,

so I don’t think the result would change even when considering download time. 🤔

difference of code

// jscodeshift
function transformLodashFunctionImports(root: Collection, j: JSCodeshift): boolean {
  const lodashFunctionImports = root.find(j.ImportDeclaration).filter(path => {
    const source = path.node.source.value;
    return typeof source === 'string' && source.startsWith('lodash/');
  });

  if (lodashFunctionImports.length === 0) {
    return false;
  }

  lodashFunctionImports.replaceWith(path => {
    const { node } = path;
    const modulePath = node.source.value as string;
    const functionName = modulePath.replace('lodash/', '');

    if (node.specifiers && node.specifiers[0] && node.specifiers[0].local) {
      const localIdentifier = node.specifiers[0].local;

      return j.importDeclaration(
        [j.importDefaultSpecifier(localIdentifier)],
        j.literal(`es-toolkit/compat/${functionName}`)
      );
    }
    return node;
  });

  return true;
}
// ast-grep
function transformLodashFunctionImports(code: string): string {
  const sg = require("@ast-grep/napi");
  const ast = sg.parse(code, "typescript");

  // 패턴 매칭: import $NAME from 'lodash/$FUNC'
  const rule = {
    pattern: "import $NAME from 'lodash/$FUNC'",
  };

  return ast.replace(rule, "import $NAME from 'es-toolkit/compat/$FUNC'");
}

Since our project only requires simple codemods,
I prefer ast-grep for its readability and lower learning curve.

What are your thoughts? 🙏 🙏 🙏

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions