import/no-cycle Restriction
它的作用
🌐 What it does
确保通过其依赖无法解析回到此模块的路径。
🌐 Ensures that there is no resolvable path back to this module via its dependencies.
这包括深度为1的循环(导入的模块导入我)到“∞”(或无限大),如果未设置 maxDepth 选项。
🌐 This includes cycles of depth 1 (imported module imports me) to "∞" (or Infinity), if the maxDepth option is not set.
这为什么不好?
🌐 Why is this bad?
依赖循环会导致架构混乱,从而使得错误难以发现。常见情况是导入一个由循环依赖引起的 undefined 值。
🌐 Dependency cycles lead to confusing architectures where bugs become hard to find. It is common to import an undefined value that is caused by a cyclic dependency.
例子
🌐 Examples
此规则的 错误 代码示例:
🌐 Examples of incorrect code for this rule:
// dep-b.js
import "./dep-a.js";
export function b() {
/* ... */
}// dep-a.js
import { b } from "./dep-b.js"; // reported: Dependency cycle detected.
export function a() {
/* ... */
}在这个例子中,dep-a.js 和 dep-b.js 相互导入,形成了循环依赖,这是有问题的。
🌐 In this example, dep-a.js and dep-b.js import each other, creating a circular dependency, which is problematic.
此规则的正确代码示例:
🌐 Examples of correct code for this rule:
// dep-b.js
export function b() {
/* ... */
}// dep-a.js
import { b } from "./dep-b.js"; // no circular dependency
export function a() {
/* ... */
}在这个修复版本中,dep-b.js 不再导入 dep-a.js,从而打破了循环。
🌐 In this corrected version, dep-b.js no longer imports dep-a.js, breaking the cycle.
配置
🌐 Configuration
此规则接受一个具有以下属性的配置对象:
🌐 This rule accepts a configuration object with the following properties:
allowUnsafeDynamicCyclicDependency
类型:boolean
🌐 type: boolean
默认:false
🌐 default: false
如果链中至少有一个动态导入,则允许循环依赖
🌐 Allow cyclic dependency if there is at least one dynamic import in the chain
ignoreExternal
类型:boolean
🌐 type: boolean
默认:false
🌐 default: false
忽略外部模块
🌐 Ignore external modules
ignoreTypes
类型:boolean
🌐 type: boolean
默认:true
🌐 default: true
忽略仅类型导入
🌐 Ignore type-only imports
maxDepth
类型:integer
🌐 type: integer
默认:4294967295
🌐 default: 4294967295
要遍历的最大依赖深度
🌐 Maximum dependency depth to traverse
如何使用
🌐 How to use
要通过配置文件或命令行启用此规则,你可以使用:
🌐 To enable this rule using the config file or in the CLI, you can use:
{
"plugins": ["import"],
"rules": {
"import/no-cycle": "error"
}
}oxlint --deny import/no-cycle --import-plugin参考文献
🌐 References
