How to write ast-grep rules in these case?

33 views Asked by At

I am using ast-grep to refactor my javascript code, but in some cases, I don't know how to write ast-grep rules to fix them.

const a = require(`${ROOT}/common`) // expect to be: const a = require('@/common')

const b = require(`@/utils/index.js`) // expect to be: const b = require('@/utils')

I try to fix the case in ast-grep playground.

My expect:

const a = require(`${ROOT}/common`) // expect to be: const a = require('@/common')

const b = require(`@/utils/index.js`) // expect to be: const b = require('@/utils')
1

There are 1 answers

0
Brenner On

I find the answer in ast-grep docs. I can use transform api to fix

answer link

fix detail:

In essence, this rule is designed to find require calls with a specific pattern and transform the argument by taking a substring and then fixing the call by prepending an '@' to the argument. This could be part of a larger effort to standardize the way modules are required in a codebase.

Here's a breakdown of the rule:

  • Rule Section: It defines a set of conditions that must all be met (all clause) for the rule to apply.

    • pattern: require($A): This looks for any require function calls with a single argument and assigns that argument to variable $A.
    • regex: require\(${ROOT}.+\): This uses a regular expression to match require function calls that use template literals with a variable ROOT at the beginning, followed by any other characters.
  • Transform Section: It specifies how to transform the code if the rule conditions are met.

    • B: This creates a new variable B.
    • substring: This operation takes a substring of variable $A.
    • source: $A: The source string is the value captured in $A.
    • startChar: 8: The substring starts from the 8th character of $A.
    • endChar: -1: The substring ends one character before the end of $A.
  • Fix Section: It defines the code replacement that should be made if the rule is triggered.

    • require('@$B'): This replaces the original require call with a new one that has '@' prepended to the transformed argument $B.