首页 > 解决方案 > 如何避免 VsCode Prettier 用箭头函数破坏链函数?

问题描述

我正在使用 VSCode 和 Prettier,当我们在内部像 lodash 链一样使用箭头函数进行链接函数调用时:

let total = _(credits).filter(c => c.active).sumBy(c => c.fee);

更漂亮的闯入:

discount = _(credits)
    .filter(c => c.active)
    .sumBy(c => c.fee);

当我们使用strings而不是箭头函数时,它不会分成几行,例如:

let total = _(credits).filter('c => c.active').sumBy('c => c.fee');

我正在使用以下.prettierrc"prettier": "^2.0.5"

{
  "singleQuote": true,
  "trailingComma": "all",
  "printWidth": 280,
  "tabWidth": 4,
  "arrowParens": "avoid",
}

当函数内部有箭头函数时,如何避免更漂亮的换行?

标签: typescriptvisual-studio-codeprettier

解决方案


没有选项可以覆盖方法链中断行为。在 2.0 版中,Prettier 使用一种新的启发式方法来确定何时中断方法链。您可以在https://github.com/prettier/prettier/pull/6685/files#diff-207f1974ddc06ae7b574152f9afc878dR893中看到启发式。

如果参数不平凡,Prettier 会中断方法链。字符串文字被认为是“平凡的”,但箭头函数表达式被认为是“非平凡的”。这就是您在将字符串与箭头函数作为参数传递时看到不同行为的原因。


推荐阅读