简体   繁体   中英

How to modify the javascript AST in an eslint rule fix

I am currently working on an eslint rule whose fix should strip a chained attributes.

In the current example b should be stripped, so

a.b() // or
a.b.c()

should become:

a() // or
a.c()

My first draft naively takes the given part of the source and removes the unwanted attribute:

fix: fixer => {
  const range = getChainedAttribute(node, 'b').range;
  range[0] -= 1; // strip also the prepending dot
  return fixer.remove(getChainedAttribute(node, 'b'));
}

( getChainedAttribute is a helper function which returns the chained attribute.)

Although this fix works as intended, it fails with the following exception from eslint:

Rule should not modify AST.

Actual:
[object Object]

Expected:
[object Object]

assertASTDidntChange (node_modules/eslint/lib/testers/rule-tester.js:406:24)
...

How to overcome this drawback to be able stripping a chained attribute/method?

Maybe a bit late to the party but recently had a similar issue and managed to fix it. I think the issue is in these 2 lines:

const range = getChainedAttribute(node, 'b').range;
range[0] -= 1; // strip also the prepending dot

You're changing the AST range directly, that's why eslint is complaining, if you do:

const range = [...getChainedAttribute(node, 'b').range];
range[0] -= 1; // strip also the prepending dot

That fixed it for me. Hope it helps you or future readers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM