模块
从EcmaScript2015(我们常说的ES6)开始,引入了模块的概念,TypeScript也沿用了模块的概念。模块内的方法,变量不会暴露到全局,他们有自身的作用域,想在外部使用必须使用export进行导出,并在引用模块的地方使用import导入。
模块加载器
模块是通过模块加载器加载的,在JavaScript的ES6版本之前,最常用的模块加载器是NodeJS使用的CommonJS规范和前端使用的RequireJS。而现在前端都使用ES6的模块化机制,NodeJS还在使用自己的基于CommonJS的规范,其余都已成为历史,TypeScript的模块化机制和ES6的相同。
使用模块
导出
导出声明
任何声明都能通过export关键字导出。例子:
export const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
导出语句
如果需要对导出的部分进行重命名,可以使用导出语句:
class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
export { ZipCodeValidator };
export { ZipCodeValidator as mainValidator };
导入
使用import关键字进行导入:
import { ZipCodeValidator } from "./ZipCodeValidator";
let myValidator = new ZipCodeValidator();
导入也可以使用as进行重命名。
导入CommonJS规范定义的模块
模块定义:
let numberRegexp = /^[0-9]+$/;
class ZipCodeValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
export = ZipCodeValidator;
导入:
import zip = require("./ZipCodeValidator");
作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。