newline-per-chained-call
在方法链中的每次调用后都需要一个换行符
此规则报告的一些问题可通过 --fix
命令行选项自动修复
此规则在 ESLint v8.53.0 中已弃用。请在 @stylistic/eslint-plugin-js
中使用 相应的规则。
¥This rule was deprecated in ESLint v8.53.0. Please use the corresponding rule in @stylistic/eslint-plugin-js
.
在没有换行符的单行上的链式方法调用更难阅读,因此一些开发者在链中的每个方法调用后放置一个换行符,以使其更具可读性和易于维护。
¥Chained method calls on a single line without line breaks are harder to read, so some developers place a newline character after each method call in the chain to make it more readable and easy to maintain.
让我们看一下以下完全有效(但单行)的代码。
¥Let’s look at the following perfectly valid (but single line) code.
d3.select("body").selectAll("p").data([4, 8, 15, 16, 23, 42 ]).enter().append("p").text(function(d) { return "I'm number " + d + "!"; });
但是,通过适当的新行,它变得易于阅读和理解。查看下面编写的相同代码,每次调用后都有换行符。
¥However, with appropriate new lines, it becomes easy to read and understand. Look at the same code written below with line breaks after each call.
d3
.select("body")
.selectAll("p")
.data([
4,
8,
15,
16,
23,
42
])
.enter()
.append("p")
.text(function (d) {
return "I'm number " + d + "!";
});
支持这种风格的另一个参数是,当方法链中的某些内容发生更改时,它提高了差异的清晰度:
¥Another argument in favor of this style is that it improves the clarity of diffs when something in the method chain is changed:
不太晰:
¥Less clear:
-d3.select("body").selectAll("p").style("color", "white");
+d3.select("body").selectAll("p").style("color", "blue");
更清晰:
¥More clear:
d3
.select("body")
.selectAll("p")
- .style("color", "white");
+ .style("color", "blue");
规则详情
¥Rule Details
此规则需要在方法链或深度成员访问中的每次调用后换行。不包括 instance[something]
等计算属性访问。
¥This rule requires a newline after each call in a method chain or deep member access. Computed property accesses such as instance[something]
are excluded.
选项
¥Options
此规则有一个对象选项:
¥This rule has an object option:
-
"ignoreChainWithDepth"
(默认值:2
)允许链达到指定深度。¥
"ignoreChainWithDepth"
(default:2
) allows chains up to a specified depth.
ignoreChainWithDepth
使用默认 { "ignoreChainWithDepth": 2 }
选项的此规则的错误代码示例:
¥Examples of incorrect code for this rule with the default { "ignoreChainWithDepth": 2 }
option:
/*eslint newline-per-chained-call: ["error", { "ignoreChainWithDepth": 2 }]*/
_.chain({}).map(foo).filter(bar).value();
// Or
_.chain({}).map(foo).filter(bar);
// Or
_
.chain({}).map(foo)
.filter(bar);
// Or
obj.method().method2().method3();
使用默认 { "ignoreChainWithDepth": 2 }
选项的此规则的正确代码示例:
¥Examples of correct code for this rule with the default { "ignoreChainWithDepth": 2 }
option:
/*eslint newline-per-chained-call: ["error", { "ignoreChainWithDepth": 2 }]*/
_
.chain({})
.map(foo)
.filter(bar)
.value();
// Or
_
.chain({})
.map(foo)
.filter(bar);
// Or
_.chain({})
.map(foo)
.filter(bar);
// Or
obj
.prop
.method().prop;
// Or
obj
.prop.method()
.method2()
.method3().prop;
何时不使用
¥When Not To Use It
如果你有冲突的规则,或者当你可以在一行上进行链式调用时,你可以安全地关闭此规则。
¥If you have conflicting rules or when you are fine with chained calls on one line, you can safely turn this rule off.
版本
此规则是在 ESLint v2.0.0-rc.0 中引入。