我的博客
个人资料:
AlanThinker
AlanThinker@stk.me

Typescript中的 namespace 和 module

软件开发 发表时间:2016-06-13 更新时间:2017-04-10

建议不要使用命名空间.
只使用模块. (在使用模块的时候, 文件本身就是一个模块, 不要使用 module关键字)    

因为typescript和javascript本身就是基于脚本文件的. 对于一个大项目, 要理清文件之间的依赖关系, 组好的做法就是用用export和import.  这个时候, 一个文件天然就是一个模块. 命名空间就显得多此一举和混乱了.

定义
export class ZipCodeValidator { 
}
使用
import { ZipCodeValidator } from "./ZipCodeValidator";

 
 

​注意:     
* 从 TypeScript 1.5开始,     内部模块改名为namespace(命名空间), 外部模块改名为module(模块).

* namespace简单, module增加了声明依赖的功能(需要加载器的配合,  比如 CommonJs/Require.js ). 

 * 大型项目推荐使用 module, 而不是  namespace.   但模块有一个限制, 每个ts文件就是一个独立的模块, 没办法将一个模块写在多个ts文件中. (为了让编译后的js可以更好的和加载器配合.)
 
* 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 {).

* 如果某个文件的顶层使用了 import * as AAA from  "AAA"; 或者 import  AAA  =  require("AAA");   这样的语法, 那么当前js文件也将变成一个模块.
不过 import A=B.A; 这样的语法并不是真正的导入语法, 只是alias而已.        
* 如果使用了export 关键字, 那么当前js文件也将变成一个模块.      

文档:

 

Modules

https://www.typescriptlang.org/docs/handbook/modules.html

​https://tslang.cn/docs/handbook/modules.html
 

Namespaces

https://www.typescriptlang.org/docs/handbook/namespaces.html

 

Namespaces and Modules

https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html
 

Module Resolution

https://www.typescriptlang.org/docs/handbook/module-resolution.html
 
IP Address: 43.129.217.254