Skip to content
← Back to rules

import/no-cycle Restriction

功能说明

确保没有通过其依赖项可解析回此模块的路径。

这包括深度为 1 的循环(被导入的模块导入我)到实际上 无限的值(如果未设置 maxDepth 选项)。

为什么这样做是不好的?

依赖循环会导致令人困惑的架构,使得 bug 难以找到。 常见的是导入由循环依赖引起的 undefined 值。

示例

此规则的错误代码示例:

javascript
// dep-b.js
import "./dep-a.js";
export function b() {
  /* ... */
}
javascript
// dep-a.js
import { b } from "./dep-b.js"; // 报告:检测到依赖循环。
export function a() {
  /* ... */
}

在此示例中,dep-a.jsdep-b.js 相互导入,创建了循环依赖,这是有问题的。

此规则的正确代码示例:

javascript
// dep-b.js
export function b() {
  /* ... */
}
javascript
// dep-a.js
import { b } from "./dep-b.js"; // 没有循环依赖
export function a() {
  /* ... */
}

在此修正版本中,dep-b.js 不再导入 dep-a.js,打破了循环。

配置

此规则接受具有以下属性的配置对象:

allowUnsafeDynamicCyclicDependency

类型:boolean

默认值:false

如果链中至少有一个动态导入,则允许循环依赖

ignoreExternal

类型:boolean

默认值:false

忽略外部模块

ignoreTypes

类型:boolean

默认值:true

忽略仅类型的导入

maxDepth

类型:integer

默认值:4294967295

要遍历的最大依赖深度

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "plugins": ["import"],
  "rules": {
    "import/no-cycle": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["import"],
  rules: {
    "import/no-cycle": "error",
  },
});
bash
oxlint --deny import/no-cycle --import-plugin

版本

此规则在 v0.0.13 中添加。

参考