簡體   English   中英

如何在 eslint 規則修復中修改 javascript AST

[英]How to modify the javascript AST in an eslint rule fix

我目前正在研究一個 eslint 規則,它的修復應該去除一個鏈式屬性。

在當前示例中b應該被剝離,所以

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

應該變成:

a() // or
a.c()

我的初稿天真地采用了源的給定部分並刪除了不需要的屬性:

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

getChainedAttribute是一個返回鏈接屬性的輔助函數。)

雖然此修復程序按預期工作,但由於 eslint 出現以下異常而失敗:

Rule should not modify AST.

Actual:
[object Object]

Expected:
[object Object]

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

如何克服這個缺點以便能夠剝離鏈接的屬性/方法?

也許參加聚會有點晚了,但最近遇到了類似的問題並設法解決了。 我認為問題出在這兩行中:

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

您正在直接更改 AST 范圍,這就是eslint抱怨的原因,如果您這樣做:

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

這對我來說是固定的。 希望對您或未來的讀者有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM