Skip to content
← Back to rules

import/prefer-default-export 风格

它的作用

在导出文件时,此规则检查是否存在默认导出。

为什么这是个问题?

此规则的存在是为了通过在模块仅有一个导出时优先使用默认导出,来标准化模块的导出方式,从而提高代码的可读性和可维护性。

示例

{ target: "single" } 选项下的 错误 代码示例:

js
export const foo = "foo";

{ target: "single" } 选项下的 正确 代码示例:

js
export const foo = "foo";
const bar = "bar";
export default bar;

{ target: "any" } 选项下的 错误 代码示例:

js
export const foo = "foo";
export const baz = "baz";

{ target: "any" } 选项下的 正确 代码示例:

js
export default function bar() {}

配置

此规则接受一个配置对象,包含以下属性:

target

type: "single" | "any"

default: "single"

用于指定优先使用默认导出的目标类型。

  • "single":当模块中只有一个导出时,优先使用默认导出。
  • "any":在任何包含导出的模块中都优先使用默认导出。

如何使用

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

json
{
  "plugins": ["import"],
  "rules": {
    "import/prefer-default-export": "error"
  }
}
bash
oxlint --deny import/prefer-default-export --import-plugin

参考资料