Skip to content
← Back to rules

eslint/func-style 风格

An auto-fix is available for this rule.

它的作用

强制一致地使用函数声明或赋值给变量的函数表达式。

为什么这是个问题?

此规则强制使用特定类型的函数风格,即函数声明或赋值给变量的函数表达式。 您可以在配置中指定自己偏好的风格。

示例

js
// 函数声明
function doSomething() {
  // ...
}

// 赋值给变量的箭头函数表达式
const doSomethingElse = () => {
  // ...
};

// 赋值给变量的函数表达式
const doSomethingAgain = function () {
  // ...
};

使用默认 "expression" 选项时,以下代码为 错误 示例:

js
/* func-style: ["error", "expression"] */

function foo() {
  // ...
}

使用 "declaration" 选项时,以下代码为 错误 示例:

js
/* func-style: ["error", "declaration"] */
var foo = function () {
  // ...
};

var foo = () => {};

使用 "declaration"{"overrides": { "namedExports": "expression" }} 选项时,以下代码为 错误 示例:

js
/* func-style: ["error", "declaration", { "overrides": { "namedExports": "expression" } }] */
export function foo() {
  // ...
}

使用 "expression"{"overrides": { "namedExports": "declaration" }} 选项时,以下代码为 错误 示例:

js
/* func-style: ["error", "expression", { "overrides": { "namedExports": "declaration" } }] */
export var foo = function () {
  // ...
};

export var bar = () => {};

使用默认 "expression" 选项时,以下代码为 正确 示例:

js
/* func-style: ["error", "expression"] */
var foo = function () {
  // ...
};

使用 "declaration" 选项时,以下代码为 正确 示例:

js
/* func-style: ["error", "declaration"] */
function foo() {
  // ...
}
// 方法(赋值给对象的函数)不受此规则检查
SomeObject.foo = function () {
  // ...
};

使用 "declaration"{ "allowArrowFunctions": true } 选项时,以下代码为额外的 正确 示例:

js
/* func-style: ["error", "declaration", { "allowArrowFunctions": true }] */
var foo = () => {};

使用 "declaration"{"overrides": { "namedExports": "expression" }} 选项时,以下代码为 正确 示例:

js
/* func-style: ["error", "declaration", { "overrides": { "namedExports": "expression" } }] */
export var foo = function () {
  // ...
};
export var bar = () => {};

使用 "expression"{"overrides": { "namedExports": "declaration" }} 选项时,以下代码为 正确 示例:

js
/* func-style: ["error", "expression", { "overrides": { "namedExports": "declaration" } }] */
export function foo() {
  // ...
}

使用 {"overrides": { "namedExports": "ignore" }} 选项时,以下代码为 正确 示例:

js
/* func-style: ["error", "expression", { "overrides": { "namedExports": "ignore" } }] */
export var foo = function () {
  // ...
};

export var bar = () => {};
export function baz() {
  // ...
}

配置

第一个选项

type: "expression" | "declaration"

第二个选项

此选项是一个包含以下属性的对象:

allowArrowFunctions

type: boolean

default: false

当为 true 时,无论风格设置如何,都允许使用箭头函数。

allowTypeAnnotation

type: boolean

default: false

当为 true 时,无论风格设置如何,都允许使用带有类型注解的函数。

overrides

type: object

overrides.namedExports

type: "ignore" | "expression" | "declaration"

default: null

如何使用

要通过配置文件或在 CLI 中 启用 此规则,可以使用:

json
{
  "rules": {
    "func-style": "error"
  }
}
bash
oxlint --deny func-style

参考资料