📜  命名空间与模块

📅  最后修改于: 2021-01-11 12:50:27             🧑  作者: Mango

命名空间和模块之间的区别

命名空间

命名空间是一种用于功能逻辑分组的方法。它使我们能够以更简洁的方式组织代码。名称空间可以包括接口,类,函数和变量,以支持一组相关功能。

与JavaScript不同,名称空间内置在TypeScript中。在JavaScript中,变量声明进入全局范围。如果在同一项目中使用了多个JavaScript文件,则有可能通过用相似的名称覆盖新用户而使新用户感到困惑。因此,使用TypeScript名称空间可以消除命名冲突

一个命名空间可以跨越多个文件,并允许使用“ –outFile”连接每个文件,因为它们都是在一个地方定义的。

命名空间声明

文件名: StoreCalc.ts

namespace invoiceCalc { 
   export namespace invoiceAccount { 
      export class Invoice { 
         public calculateDiscount(price: number) { 
            return price * .60; 
         } 
      } 
   } 
}

访问命名空间

///
let invoice = new invoiceCalc.invoiceAccount.Invoice(); 
console.log("Output: "" +invoice.calculateDiscount(400));

要了解更多信息,请单击此处

模组

模块是一种创建一组相关变量,函数,类和接口等的方法。它在本地范围而不是全局范围内执行。换句话说,在模块中声明的变量,函数,类和接口不能直接在模块外部访问。我们可以使用export关键字创建一个模块,也可以通过使用import关键字在其他模块中使用。

模块通过使用模块加载器导入另一个模块。在运行时,模块加载程序负责在执行模块之前查找并执行模块的所有依赖关系。 JavaScript中最常用的模块加载器是Node.js的CommonJS模块加载器,Web应用程序的require.js。

模块声明

文件名: additional.ts

export class Addition{
    constructor(private x?: number, private y?: number){
    }
    Sum(){
        console.log("SUM: " +(this.x + this.y));
    }
}

访问模块

import {Addition} from './addition';
let addObject = new Addition(10, 20); 
addObject.Sum();

要了解更多信息,请单击此处

模块与命名空间

SN Module Namespace
1. A module is a way which is used to organize the code in separate files and can execute in their local scope, not in the global scope. A namespace is a way which is used for logical grouping of functionalities with local scoping.
2. A Module uses the export keyword to expose module functionalities. We can create a namespace by using the namespace keyword and all the interfaces, classes, functions, and variables can be defined in the curly braces{} by using the export keyword.
3. All the exports functions and classes in a module are accessible outside the module. We must use the export keyword for functions and classes to be able to access it outside the namespace.
4. We can use a module in other modules by using the import keyword. The namespace must be included in a file by using triple-slash (///) reference syntax. e.g.
/// 
5. It is also known as an external module. It is also known as an internal module.
6. We can compile the module by using the “–module” command. We can compile the namespace by using the “–outFile” command.
7. Modules import another module by using a module loader API, which was specified at the time of compilation, e.g., CommonJS, require.js, etc. In namespace, there is no need for a module loader. Include the .js file of a namespace using the