How do I use namespaces with TypeScript external modules?

前端 未结 9 1407
陌清茗
陌清茗 2020-11-22 08:59

I have some code:

baseTypes.ts

export namespace Living.Things {
  export class Animal {
    move() { /* ... */ }
  }
  export class          


        
9条回答
  •  眼角桃花
    2020-11-22 09:30

    The proper way to organize your code is to use separate directories in place of namespaces. Each class will be in it's own file, in it's respective namespace folder. index.ts will only re-export each file; no actual code should be in the index.ts file. Organizing your code like this makes it far easier to navigate, and is self-documenting based on directory structure.

    // index.ts
    import * as greeter from './greeter';
    import * as somethingElse from './somethingElse';
    
    export {greeter, somethingElse};
    
    // greeter/index.ts
    export * from './greetings.js';
    ...
    
    // greeter/greetings.ts
    export const helloWorld = "Hello World";
    

    You would then use it as such:

    import { greeter } from 'your-package'; //Import it like normal, be it from an NPM module or from a directory.
    // You can also use the following syntax, if you prefer:
    import * as package from 'your-package';
    
    console.log(greeter.helloWorld);
    

提交回复
热议问题