What's the difference between internal and external modules in TypeScript?

后端 未结 4 965
萌比男神i
萌比男神i 2020-12-14 00:05

I have spent some time reading the Typescript language specification and am somewhat confused about the difference between internal and external

4条回答
  •  醉酒成梦
    2020-12-14 00:44

    Internal Modules: namespace or module keyword

    Declaration

    An Internal module can be declared using either the namespace or the module keyword. Then we can decide which part of our internal module 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, internal modules 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 external modules (ES6 modules) to achieve this.

    The internal modules are now used for ambient namespace declarations.

    Single File Usage

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

提交回复
热议问题