ES2015 module syntax is preferred over custom TypeScript modules and namespaces @typescript-eslint/no-namespace

南楼画角 提交于 2021-02-08 12:16:28

问题


I'm receiving the following error running npm start:

ES2015 module syntax is preferred over custom TypeScript modules and namespaces @typescript-eslint/no-namespace

    namespace InternalThings {...}

I tried to research this but it's very confusing.

Why does this is happening? How to fix it?

I tried to put some flags on my tsconfig.json but so far no success;


回答1:


This is a lint error, caused by this lint rule: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-namespace.md

If you find the rule useful and want to keep it, then you'll need to modify your code to use import and export instead of namespace. See the documentation of the rule for what counts as a fix.

If you like the rule, but want to disable the rule for this line, add the following just above it:

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

If you don't like the rule and want to disable it entirely, then edit your .eslintrc file to have the following line:

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



回答2:


To fix this error, instead of:

export namespace InternalThings {
    export function myFunction() {
    }

    export class MyClass {
    }
}
import { InternalThings } from './internal-things';

InternalThings.myFunction();

you expose all the members of the namespace directly:

export function myFunction() {
}

export class MyClass {
}

and you import it like this:

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

InternalThings.myFunction();

The main idea is that users of your module can import only what they want, or name your module differently:

import * as CustomModuleName from './internal-things';

CustomModuleName.myFunction();
import { MyClass } from './internal-things';

let field = new MyClass();



回答3:


The error is coming from eslint. You have to either ignore '@typescript-eslint/no-namespace' rule in the config or rewrite your code using ES6.

Custom TypeScript modules (module foo {}) and namespaces (namespace foo {}) are considered outdated ways to organize TypeScript code. ES2015 module syntax is now preferred (import/export)

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



来源:https://stackoverflow.com/questions/58270901/es2015-module-syntax-is-preferred-over-custom-typescript-modules-and-namespaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!