模块与命名空间(内部模块)类似,不同的是模块可以声明它的依赖
-
模块
es6的模块语法与CommonJS和AMD环境不兼容,TypeScript提供了
export =
语法用于支持该环境// 通过以下语法规则可兼容 CommonJs与AMD环境 export = ZipCodeValidator; import zip = require("./ZipCodeValidator");
.d.ts
文件是外部模块声明,用于作为外部模块被引用时的解析 -
命名空间
命名空间用于组织模块内部代码
// Validation.ts namespace Validation { export interface StringValidator { isAcceptable(s: string): boolean; } } // 多个文件可以使用同一个命名空间,通过引用标签声明依赖关系 // LettersOnlyValidator.ts /// <reference path="Validation.ts" /> namespace Validation { const lettersRegexp = /^[A-Za-z]+$/; export class LettersOnlyValidator implements StringValidator { isAcceptable(s: string) { return lettersRegexp.test(s); } } }
模块解析
-
模块引用分为相对的与非相对的
-
相对导入是以
/
,./
或../
开头的import Entry from "./components/Entry";
import { DefaultHeaders } from "../constants/http";
import "/mod";
- 其他形式都是非相对
import * as $ from "jQuery";
import { Component } from "@angular/core";
- 模块解析具体规则
-
相对导入是以
-
路径映射
-
TypeScript编译器通过使用
tsconfig.json
文件里的"paths"
来支持这样的声明映射(取别名){ "compilerOptions": { "baseUrl": ".", // This must be specified if "paths" is. "paths": { "jquery": ["node_modules/jquery/dist/jquery"] // 此处映射是相对于"baseUrl" } } }
"paths"
是相对于"baseUrl"
进行解析{ "compilerOptions": { "baseUrl": ".", "paths": { // 将多个模块集中至一处 "*": [ "*", "generated/*" // <baseUrl>/generated/<moduleName> ] } } }
-
-
rootDirs
虚拟目录- 每当编译器在某一
rootDirs
的子目录下发现了相对模块导入,它就会尝试从每一个rootDirs
中导入
- 每当编译器在某一
JavaScript文件类型检查
-
用JSDoc类型表示类型信息 函数参数
@param
等 注释写法可查