【问题标题】:ES2015 module syntax is preferred over custom TypeScript modules and namespaces @typescript-eslint/no-namespaceES2015 模块语法优于自定义 TypeScript 模块和命名空间@typescript-eslint/no-namespace
【发布时间】:2020-02-04 19:53:23
【问题描述】:

我在运行 npm start 时收到以下错误:

ES2015 模块语法优于自定义 TypeScript 模块和命名空间@typescript-eslint/no-namespace

    namespace InternalThings {...}

我试图对此进行研究,但它非常令人困惑。

为什么会这样? 如何解决?

我尝试在我的 tsconfig.json 上添加一些标志,但到目前为止没有成功;

【问题讨论】:

    标签: javascript node.js reactjs typescript


    【解决方案1】:

    这是一个 lint 错误,由以下 lint 规则引起:https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-namespace.md

    如果您发现该规则有用并希望保留它,那么您需要修改您的代码以使用importexport 而不是命名空间。请参阅该规则的文档,了解什么是修复。

    如果您喜欢该规则,但想禁用该行的规则,请在其上方添加以下内容:

    // eslint-disable-next-line @typescript-eslint/no-namespace
    

    如果您不喜欢该规则并想完全禁用它,请编辑您的 .eslintrc 文件以包含以下行:

    rules: {
      "@typescript-eslint/no-namespace": "off"
    }
    

    【讨论】:

    • 你能提供你从文档中看到的修复吗?
    • 忽略规则不是最好的解决方案。通过正确的导入修复它。
    【解决方案2】:

    要修复此错误,而不是:

    export namespace InternalThings {
        export function myFunction() {
        }
    
        export class MyClass {
        }
    }
    
    import { InternalThings } from './internal-things';
    
    InternalThings.myFunction();
    

    你直接暴露命名空间的所有成员:

    export function myFunction() {
    }
    
    export class MyClass {
    }
    

    然后你像这样导入它:

    import * as InternalThings from './internal-things';
    
    InternalThings.myFunction();
    

    主要思想是您的模块的用户可以只导入他们想要的内容,或者以不同的方式命名您的模块:

    import * as CustomModuleName from './internal-things';
    
    CustomModuleName.myFunction();
    
    import { MyClass } from './internal-things';
    
    let field = new MyClass();
    

    【讨论】:

      【解决方案3】:

      错误来自 eslint。您必须忽略配置中的“@typescript-eslint/no-namespace”规则或使用 ES6 重写代码。

      自定义 TypeScript 模块 (module foo {}) 和命名空间 (namespace foo {}) 被认为是组织 TypeScript 代码的过时方式。 现在首选 ES2015 模块语法(导入/导出)

      参考https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-namespace.md

      【讨论】:

        猜你喜欢
        • 2022-10-04
        • 2021-01-10
        • 1970-01-01
        • 2016-07-17
        • 2019-04-30
        • 2016-02-25
        • 2016-08-22
        • 1970-01-01
        • 2021-02-06
        相关资源
        最近更新 更多