简体   繁体   中英

Replace TypeScript namespaces with ES2015 modules

I've recently reconfigured my typescript setup and now I get errors that are cause through the rule no-namespace .

My current setup with namespaces is the following:

class that exports something:

namespace MyNamespace {
    export class Foo {}
    export class Bar {}
}

class that imports:

import MyNamespace from './my-namespace';

// access classes
MyNamespace.Foo;
MyNamespace.Bar;

I want to replace this setup with the recommended ES2015 modules (I do not want to simply disable the rule). How would I do that? Optimally, I want to keep my current import syntax, I do not particularly like the syntax import {Foo, Bar} from './my-namespace' .

If you want to namespace your imports, use the * as... import syntax:

export class Foo {}
export class Bar {}
import * as MyNamespace from './my-namespace';

// access classes
MyNamespace.Foo;
MyNamespace.Bar;

If you are using export , you can do sth as @cyr_x mentioned. Just want to point out using export default is also ok to use namespace.

export {default as YourCustomisedName} from '<your file path>'

Here is the official answer .

In your example, you can replace the namespaces with modules like so:

  1. Remove the namespace syntax:
    //namespace MyNamespace {   <-- remove this line
    export class Foo {}
    export class Bar {}
    //}                         <-- remove this line
  1. In the file where you need the types, use a named import:
import * as MyNamespace from './my-namespace';

// access classes
MyNamespace.Foo;
MyNamespace.Bar;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM