"内部模块"现在称做"命名空间"。 "外部模块"现在则简称为"模块"
1. 导出
任何声明(比如变量,函数,类,类型别名或者接口) 都能通过添加 export
关键字来导出
Copy export interface StringValidator {
isAcceptable(s: string): boolean;
}
2. 导入
具有副作用的导入模块
尽管不推荐这么做,一些模块会设置一些全局状态供其它模块使用。 这些模块可能没有任何的导出或用户根本就不关注它的导出。 使用下面的方法来导入这类模块:
Copy import "./my-module.js";
import './index.less';
3. TypeScript 中的导入导出
当前导入(import)导入(export)的语法,并不兼容 CommonJS 中的 exports
, 因此, TypeScript 引入了 export =
和 import = require()
的语法
使用 export =
导出对象,这里的对象指,类,接口,命名空间 ,函数或枚举. 如果使用 export =
导出,必须使用import module = require('module')
来导入
Copy let numberRegexp = /^[0-9]+$/;
class ZipCodeValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
export = ZipCodeValidator; // 导出
import zip = require("./ZipCodeValidator"); // 导入
new zip().isAcceptable(str);
4. 将 TypeScript 模块转为其它模块代码
示例: tsc --module commonjs Test.ts
TypeScript源码:
Copy import m = require("mod");
export let t = m.something + 1;
转换为 AMD/ RequireJS
Copy define(["require", "exports", "./mod"], function (require, exports, mod_1) {
exports.t = mod_1.something + 1;
});
转换为 CommonJS/Node
Copy let mod_1 = require("./mod");
exports.t = mod_1.something + 1;
转化为 UMD
Copy (function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
let v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "./mod"], factory);
}
})(function (require, exports) {
let mod_1 = require("./mod");
exports.t = mod_1.something + 1;
});
转换为 System 模块
Copy System.register(["./mod"], function(exports_1) {
let mod_1;
let t;
return {
setters:[
function (mod_1_1) {
mod_1 = mod_1_1;
}],
execute: function() {
exports_1("t", t = mod_1.something + 1);
}
}
});
转换为 es6 import
Copy import { something } from "./mod";
export let t = something + 1;
5. 可选的模块加载和其它高级加载场景
外部模块
在 Node 中大部分工作通过加载的模块实现的,我们可以使用顶级的 export
声明来为每个模块定义一个 .d.ts
文件, 也可以在一个 .d.ts
文件中完成。
当遇到多个模块时,我们使用与构造一个外部命名空间类似的方法,使用 module
关键字并将名字用引号括起来,方便之后 import。 如:
Copy declare module "url" {
export interface Url {
protocol?: string;
hostname?: string;
pathname?: string;
}
export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url;
}
declare module "path" {
export function normalize(p: string): string;
export function join(...paths: any[]): string;
export let sep: string;
}
使用:
Copy /// <reference path="node.d.ts"/>
import * as URL from "url";
let myUrl = URL.parse("http://www.typescriptlang.org");
模块声明通配符
当加载一些非 JS 内容时,通常会使用一个前缀或者后缀来表示特殊的加载语法,这时候就要用到模块声明通配符
Copy declare module "*!text" {
const content: string;
export default content;
}
// Some do it the other way around.
declare module "json!*" {
const value: any;
export default value;
}
现在就可以加载匹配"!text"或"json! "的内容了。
Copy import fileContent from "./xyz.txt!text";
import data from "json!http://example.com/data.json";
console.log(data, fileContent);