禁止 require 導入
禁止呼叫
require()
。
偏好 require()
的 ES6 風格新式導入。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-require-imports": "error"
}
};
在遊戲場中嘗試此規則 ↗
範例
- ❌ 不正確
- ✅ 正確
選項
此規則接受下列選項
type Options = [
{
/** Patterns of import paths to allow requiring from. */
allow?: string[];
},
];
const defaultOptions: Options = [{ allow: [] }];
allow
一個字串陣列。此字串會編譯到有 u
標記的正規程式,並拿來與導入的路徑測試。普遍的用例是允許導入 package.json
,這是因為 package.json
通常存在於 TS 根目錄之外,因此靜態導入可能會導致根目錄衝突,特別是在啟用 resolveJsonModule
時。您也可以用來允許導入任何 JSON(如果您的環境不支援 JSON 模組)或用於 import
陳述式無法執行的其他情況。
使用 {allow: ['/package\\.json$']}
- ❌ 不正確
- ✅ 正確
什麼時候不使用它
如果你的程式專案經常使用舊版的 CommonJS require
,那麼此規則可能不適用於你。假設只有專案的一部分會用到 require
,那麼你不妨考慮針對那些特定情況使用 ESLint 停用註解,而不是完全停用此規則。