因为在 js、ts 中,每个文件就是一个 module,凡是通过 import 或者 require 对应的路径,都是一个 module。
export = and import = require()
// ZipCodeValidator.ts
let numberRegexp = /^[0-9]+$/;
class ZipCodeValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
export = ZipCodeValidator;
// Test.ts
import zip = require("./ZipCodeValidator");
Working with Other JavaScript Libraries
对于没有使用 ts 编写的第三方库,我们可以使用 .d.ts
文件。我们可以为每个 module 声明一个 .d.ts
文件。
// node.d.ts
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 var sep: string;
}
--------------
import tool from 'Src/const/tool'
declare module 'Src/const/tool' {
}
Now we can /// <reference> node.d.ts
and then load the modules
/// <reference path="node.d.ts"/>
import * as URL from "url";
let myUrl = URL.parse("http://www.typescriptlang.org");
如果我们不想对某个 modules 声明具体的类型,可以直接像下面这样:
declare module "hot-new-module"; // hot-new-module 中的任何导出的变量类型都是 any
import x, { y } from "hot-new-module"; //x: any, y: any
导入非 js module
除了可以导入 js,还可以导入图片、字体等,如下:
import imag from 'test.svg'
对于这些非 js module,可以像下面这样为其声明类型:
declare module "*.svg" {
const content: string;
export default content;
}