Why are some Typescript module names given as strings?

后端 未结 2 1218
情歌与酒
情歌与酒 2021-01-21 06:47

Typically, Typescript modules are declared like

declare module MyModule {
     ....
}

but sometimes I also see it like

declare         


        
相关标签:
2条回答
  • 2021-01-21 07:08

    As outlined in the Typescript docs, there is a difference between the two styles. module x { is equivalent to namespace x {, while module "x" { is unlike either of the other two. This is definitely confusing, which is why the documentation using the latter syntax in all cases.

    The question then must be asked, what is the difference between a namepsace and a so-called external module (i.e., a module that is declared with quotes)?

    We get some insight from the docs:

    Just like namespaces, modules can contain both code and declarations. The main difference is that modules declare their dependencies.

    Modules also have a dependency on a module loader (such as CommonJs/Require.js).

    Essentially, using the quotes indicates that it is indeed a module in the traditional Javascript sense that requires explicit import to be used. Without the quotes, you just create a global object that can be referenced and utilized without any explicit requires.

    0 讨论(0)
  • 2021-01-21 07:29

    As the offical docs described, now

    "Internal modules" === “namespaces”

    “External modules” === “modules”

    A note about terminology: It’s important to note that in TypeScript 1.5, the nomenclature has changed. “Internal modules” are now “namespaces”. “External modules” are now simply “modules”, as to align with ECMAScript 2015’s terminology, (namely that module X { is equivalent to the now-preferred namespace X {).

    Here, I will show you some demos codes, may be it can make this more easy to understand!

    /*
    Note: All of these files in the same folder, i.e. the same path!
    */
    
    // declare a namespace, demoNamespace.d.ts
    declare namespace "DemoNamespace" {
        export function fn(): string;
    }
    
    // using a namespace, demoNamespaceModule.ts
    import * as n from "demoNamespace";
    
    //let f = new n.DemoNamespace.fn(); ???
    
    
    // export a module, demoModule.ts
    export class Alpha { /* ... */ }
    export class Beta { /* ... */ }
    
    // using a module, demoModuleTest.ts
    import * as m from "./demoModule";
    
    let a = new m.Alpha();
    let b = new m.Beta();
    

    references links:

    namespaces-and-modules namespaces modules

    0 讨论(0)
提交回复
热议问题