TS 中的 Module 的概念兼容 ES 2015 中 Module 的概念。
简介
模块中的代码属于模块本身的作用域,而不是全局作用域。也这就意味着没有明确的 export 的话,模块中的 变量,函数,类等对其他模块是不见的。相对的其他模块要使用某一模块的内容需要通过 import 导入。
Export
- 导出一个声明:通过在声明前加
export关键词修饰即可导出。 - 导出语句:也可以像
import语句的逆形式一样,通过类似如下的语句导出:
export { User };
export { User as BaseMember };
-
从其他模块中导出:
export { User as BaseMember } from "./users" } -
从其他模块中导出全部:
export * from ".users"
Import
- 从模块中导入单个导出:
import { User} from "./users" - 导出时重命名 :
import { User as BaseMember} from "./users" - 从模块中导入全部到一个变量名中:
import * as users from "./users" - 单纯的导入模块以执行模块:
import "./my-module.js"
Default exports
每一个模块都有一个可选的默认导出. 在 export 后面加 default 关键字。
default 导出也支持导出字面量。如: export default "123";
export = 和 import = require()
在 CommonJS 和 AMD 模块系统中都一个 exports 的变量,用来包装一个模块的所有导出。为了兼容这些模块系统。 TS 也支持 export = 的语法来导出模块的单个对象。但是注意 export = 必须和 import module = require("module") 搭配使用。
导入其他的 JS 库
在 TS 的术语中把没有定义实现的声明称之为 ambient 。这些声明一般定义在 .d.ts 文件中。你可以把他们理解成 c/c++ 中的头文件。
Ambient Modules
例如有一个名为 node.d.ts 的文件。
然后便可以将下面一样来导入:
/// <reference path="node.d.ts"/>
import * as URL from "url";
let myUrl = URL.parse("http://demo.com");
TS 也提供了不提供模块的具体的声明文,来导入 JS 库的支持。
即提供一种简写的方式:
如下 declarations.d.ts
declare module "hot-new-module";
这样模块中所有的导入的类型都将是 any 类型。
import x, {y} from "hot-new-module";
Guidance for structuring modules
-
导出层级不要太深。从模块中导出一个 namespace 加增加一个层级。如果没有必要不要增加层级 。
-
如果只导出一个单一的类或函数,使用
export default。 -
导出多个对象时,把他们放在最顶层。
-
显式的列出所有要导入的名字。
-
如果要导入很多的东西的时候,可以考虑使用 namespace 导入模式。
如import * as largeModule from "./MyLargeModule.ts"; -
通过 re-export 来扩展。
-
不要在模块中使用 namespaces。
参考: Modules








网友评论