Module vs Namespace - Import vs Require Typescript

后端 未结 5 1252
攒了一身酷
攒了一身酷 2020-12-04 05:14

I am getting lot of confusion with module/namespace/export and import, require, reference usage. Being from Java background, Can someone explain me

5条回答
  •  臣服心动
    2020-12-04 05:48

    Naming Confusion

    In the early days of Typescript, the namespaces were called internal modules and the ES6 Modules were called external modules.

    Now for declaring the namespaces, the Typescript team recommends using the namespace { } instead of the module { } syntax to avoid the naming confusion with the external modules. Because the external modules are now simply 'modules' and internal modules are 'namespaces'.


    Namespaces

    Declaration

    A namespace in Typescript can be declared using either the namespace or the module keyword. Both the keywords do the same thing. Then we can decide which part of our namespace to make public using the export keyword.

    // LivingThings.ts
    export namespace Animals {
        export class Dog { }
        export class Cat { }
    }
    export namespace Plants {
        export class Orchid { }
        export class Bamboo { }
    }
    
    // LivingThingsUser.ts
    import { Animals, Plants } from "./LivingThings"
    

    Logical Grouping

    Before ES6, the namespaces were used in Typescript for encapsulating the interfaces, classes, functions and variables to support a group of related functionalities and hide implementation details. This way we could prevent variables from leaking into the global space. This helped in better code organisation and prevent name collisions. Now it is recommended to use ES6 modules to achieve this.

    The namespaces are now used for ambient namespace declarations.

    Single File Usage

    We can declare namespaces across multiple files and they can be concatenated using --outFile flag. We can then use that concatenated file inside the

提交回复
热议问题