no-namespace
Disallow TypeScript namespaces.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/recommended"
可启用此规则。
TypeScript 历史上允许一种称为 "定制模块" (module Example {}
) 的代码组织形式,后来重命名为 "namespaces" (namespace Example
)。
命名空间是一种过时的组织 TypeScript 代码的方式。
现在首选 ES2015 模块语法 (import
/export
)。
英:TypeScript historically allowed a form of code organization called "custom modules" (module Example {}
), later renamed to "namespaces" (namespace Example
).
Namespaces are an outdated way to organize TypeScript code.
ES2015 module syntax is now preferred (import
/export
).
此规则不报告使用 TypeScript 模块声明来描述外部 API (
declare module 'foo' {}
)。
module.exports = {
"rules": {
"@typescript-eslint/no-namespace": "error"
}
};
示例
具有默认选项的代码示例:
英:Examples of code with the default options:
- ❌ 不正确
- ✅ 正确
module foo {}
namespace foo {}
declare module foo {}
declare namespace foo {}
Open in Playgrounddeclare module 'foo' {}
// anything inside a d.ts file
Open in Playground选项
allowDeclarations
带有 { "allowDeclarations": true }
选项的代码示例:
英:Examples of code with the { "allowDeclarations": true }
option:
- ❌ 不正确
- ✅ 正确
module foo {}
namespace foo {}
Open in Playgrounddeclare module 'foo' {}
declare module foo {}
declare namespace foo {}
declare global {
namespace foo {}
}
declare module foo {
namespace foo {}
}
Open in Playground{ "allowDeclarations": false }
选项的代码示例:
英:Examples of code for the { "allowDeclarations": false }
option:
- ❌ 不正确
- ✅ 正确
module foo {}
namespace foo {}
declare module foo {}
declare namespace foo {}
Open in Playgrounddeclare module 'foo' {}
Open in PlaygroundallowDefinitionFiles
{ "allowDefinitionFiles": true }
选项的代码示例:
英:Examples of code for the { "allowDefinitionFiles": true }
option:
- ❌ 不正确
- ✅ 正确
// if outside a d.ts file
module foo {}
namespace foo {}
// if outside a d.ts file and allowDeclarations = false
module foo {}
namespace foo {}
declare module foo {}
declare namespace foo {}
Open in Playgrounddeclare module 'foo' {}
// anything inside a d.ts file
Open in Playground何时不使用它
如果你的项目是在现代模块和命名空间之前构建的,则可能很难迁移出命名空间。 在这种情况下,你可能无法在项目的某些部分使用此规则。 你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。
英:If your project was architected before modern modules and namespaces, it may be difficult to migrate off of namespaces. In that case you may not be able to use this rule for parts of your project. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.
进一步阅读
选项
该规则接受以下选项
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 },
];