跳到內容

import/no-cycle 限制

功能

確保沒有可解析的路徑,透過其依賴項返回此模組。

這包含深度為 1(導入的模組導入我)到「∞」(或無限)的循環,如果未設定 maxDepth 選項。

為何這不好?

依賴循環會導致令人困惑的架構,其中錯誤變得難以尋找。 導入由循環依賴引起的 undefined 值是很常見的。

範例

此規則的不正確程式碼範例

javascript
// dep-b.js
import "./dep-a.js";
export function b() {
  /* ... */
}
javascript
// dep-a.js
import { b } from "./dep-b.js"; // reported: Dependency cycle detected.
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"; // no circular dependency
export function a() {
  /* ... */
}

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

參考資料

根據 MIT 許可發布。