避免命名空間
禁止 TypeScript 命名空間。
✅
延伸 “plugin:@typescript-eslint/建議"
在 ESLint 設定檔中 啟用此規則。
歷史上,TypeScript 允許一種稱為「自訂模組」(module Example {}
) 的程式碼組織形式,後來更名為「命名空間」(namespace Example
)。命名空間是一種過時的 TypeScript 程式碼組織方式。現在建議使用 ES2015 模組語法 (import
/export
)。
此規則不會回報使用 TypeScript 模組宣告描述外部 API (
declare module 'foo' {}
) 的情況。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-namespace": "error"
}
};
在測試場中嘗試此規則 ↗
範例
使用預設選項的程式碼範例
- ❌ 錯誤
- ✅ 正確
選項
本規則接受以下選項
type Options = [
{
/** Whether to allow `declare` with custom TypeScript namespaces. */
allowDeclarations?: boolean;
/** Whether to allow `declare` with custom TypeScript namespaces inside definition files. */
allowDefinitionFiles?: boolean;
},
];
const defaultOptions: Options = [
{ allowDeclarations: false, allowDefinitionFiles: true },
];
allowDeclarations
選項 { "allowDeclarations": true }
範例程式碼
- ❌ 錯誤
- ✅ 正確
選項 { "allowDeclarations": false }
範例程式碼
- ❌ 錯誤
- ✅ 正確
allowDefinitionFiles
選項 { "allowDefinitionFiles": true }
範例程式碼
- ❌ 錯誤
- ✅ 正確
何時不使用
如果你的專案是在現代模組和命名空間之前建置,那麼可能很難跳脫命名空間。這種情況下,你可能無法將此規則用於專案的各個部分。你可以考慮針對這些特定情況使用 ESLint 禁止註解,而非完全停用這條規則。