typescript imports

relative 和 non-relative import

Relative Import以/, ./../为开头. 如

import Entry from "./components/Entry";
import { DefaultHeaders } from "../constants/http";
import "/mod";

所有其他的都是为non-relative import, 如:

import * as $ from "jquery";
import { Component } from "@angular/core";

relative import引入相对于当前文件路径的文件, 且无法引入ambient module declarations. 使用relative import来引入你自己实现的文件.

non-relative import引入相对于baseUrl路径, 或者存在于路径映射(Path Mapping)中的文件, 可以引入ambient module declarations. 使用non-relative import来引入外部依赖.

模块解析策略

有两种策略: Node或Classic. 通过--moduleResolution来指定策略. 对于--module AMD | System | ES2015来说, 默认是Classic.

Classic (经典策略)

这曾是TypeScript的默认路径解析策略. 现在它主要是为了维护向后兼容性了.

对于relative import, 在文件/root/src/folder/A.ts中`import { b } from "./moduleB", 会进行如下查找:

  1. /root/src/folder/moduleB.ts
  2. /root/src/folder/moduleB.d.ts

对于non-relative import, 查找过程会从当前文件沿着文档树向上查找. 在文件/root/src/folder/A.tsimport { b } from "moduleB", 会进行如下查找:

  1. /root/src/folder/moduleB.ts
  2. /root/src/folder/moduleB.d.ts
  3. /root/src/moduleB.ts
  4. /root/src/moduleB.d.ts
  5. /root/moduleB.ts
  6. /root/moduleB.d.ts
  7. /moduleB.ts
  8. /moduleB.d.ts

Node策略

这个策略模仿Node.js的模块解析策略. Node.js的完整解析算法见这里.

Node.js如何解析模块

Node.js中调用require方法来引入模块.

require的路径为相对路径

文件/root/src/moduleA.js中通过import var x = require("./moduleB");引入模块, 查找过程如下:

  1. 文件/root/src/moduleB.js
  2. 文件夹/root/src/moduleB, 且其中有package.json文件指定了"main"模块. 如/root/src/moduleB/package.json中有{ "main": "lib/mainModule.js" }, 那么Node.js会引入/root/src/moduleB/lib/mainModule.js
  3. 文件夹/root/src/moduleB, 且其中有index.js. 这是默认的"main"模块.

更多见文件模块文件夹模块

require的路径为绝对路径

Node会从node_modules文件夹中寻找模块. node_modules可能是在源文件当前目录中, 也可能是在文件树的上层. Node会沿着文件树逐层向上寻找node_modules中的模块.

文件/root/src/moduleA.js通过import var x = require("moduleB");引入模块, 查找过程如下:

  1. /root/src/node_modules/moduleB.js
  2. /root/src/node_modules/moduleB/package.json (if it specifies a "main" property)
  3. /root/src/node_modules/moduleB/index.js
  4. /root/node_modules/moduleB.js
  5. /root/node_modules/moduleB/package.json (if it specifies a"main"` property)
  6. /root/node_modules/moduleB/index.js
  7. /node_modules/moduleB.js
  8. /node_modules/moduleB/package.json (if it specifies a "main" property)
  9. /node_modules/moduleB/index.js

更多见node_modules引入模块

TypeScript如何解析模块

TypeScript模仿了Node的解析策略, 不过针对的是.ts, .tsx.d.ts文件, 而且package.json中用"types"对应于Node中的"main".

相对路径

文件/root/src/moduleA.ts中引入import { b } from "./moduleB", 查找过程如下:

  1. /root/src/moduleB.ts
  2. /root/src/moduleB.tsx
  3. /root/src/moduleB.d.ts
  4. /root/src/moduleB/package.json (if it specifies a "types" property)
  5. /root/src/moduleB/index.ts
  6. /root/src/moduleB/index.tsx
  7. /root/src/moduleB/index.d.ts

绝对路径

文件/root/src/moduleA.ts中引入import { b } from "moduleB", 查找过程如下:

  1. /root/src/node_modules/moduleB.ts
  2. /root/src/node_modules/moduleB.tsx
  3. /root/src/node_modules/moduleB.d.ts
  4. /root/src/node_modules/moduleB/package.json (if it specifies a "types" property)
  5. /root/src/node_modules/moduleB/index.ts
  6. /root/src/node_modules/moduleB/index.tsx
  7. /root/src/node_modules/moduleB/index.d.ts
  8. /root/node_modules/moduleB.ts
  9. /root/node_modules/moduleB.tsx
  10. /root/node_modules/moduleB.d.ts
  11. /root/node_modules/moduleB/package.json (if it specifies a "types" property)
  12. /root/node_modules/moduleB/index.ts
  13. /root/node_modules/moduleB/index.tsx
  14. /root/node_modules/moduleB/index.d.ts
  15. /node_modules/moduleB.ts
  16. /node_modules/moduleB.tsx
  17. /node_modules/moduleB.d.ts
  18. /node_modules/moduleB/package.json (if it specifies a "types" property)
  19. /node_modules/moduleB/index.ts
  20. /node_modules/moduleB/index.tsx
  21. /node_modules/moduleB/index.d.ts

模块解析参数

通常, 项目中都会通过一系列的构建程序将源目录中的文件, 打包/压缩到目标目录中. 这个过程可能导致文件名或目录结构发生变化. 因此TypeScript编译器有如下几个参数应对这种变化.

Base URL

AMD模块加载器, 如requireJS, 常使用baseUrl. 源文件可以在多个目录中, 但目标文件会被放到同一个目录中.

所有non-relative import都相对于baseUrl.

baseUrl的值可以是:

  • baseUrl的命令行参数 (如果参数为相对路径, 则该参数相对于当前路径)
  • tsconfig.json中的baseUrl (如果参数为相对路径, 则该参数相对于tsconfig.json的目录)

更多见RequireJSSystemJS.

Path Mapping (路径映射)

你还可以使用tsconfig.json中的"paths"属性, 定义Path Mapping. 如:

{
  "compilerOptions": {
    "baseUrl": ".", // This must be specified if "paths" is.
    "paths": {
      "jquery": ["node_modules/jquery/dist/jquery"] // This mapping is relative to "baseUrl"
    }
  }
}

注意Path Mapping是相对于baseUrl的.

"paths"可以用来实现路径回退(Fallback)查找. 举个例子.

projectRoot
├── folder1
│   ├── file1.ts (imports 'folder1/file2' and 'folder2/file3')
│   └── file2.ts
├── generated
│   ├── folder1
│   └── folder2
│       └── file3.ts
└── tsconfig.json

tsconfig.json内容如下

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "*": [
        "*",
        "generated/*"
      ]
    }
  }
}

这个配置让编译器对满足模式"*"(即所有文件)的模块引用, 进行如下查找:

  1. "*": meaning the same name unchanged, so map <moduleName> => <baseUrl>/<moduleName>
  2. "generated/*" meaning the module name with an appended prefix “generated”, so map <moduleName> => <baseUrl>/generated/<moduleName>

所以, 对于file1.ts中的两个引用:

  • import ‘folder1/file2’
    1. "*"捕获文件名folder1/file2
    2. 尝试第一种替换, 即: "*" => folder1/file2
    3. 得到的是绝对路径, 将其与baseUrl结合, 得到projectRoot/folder1/file2.ts
    4. 文件找到, 结束.
  • import ‘folder2/file3’
    1. "*"捕获文件名folder2/file3
    2. 尝试第一种替换, 即: "*" => folder2/file3
    3. 得到的是绝对路径, 将其与baseUrl结合, 得到projectRoot/folder2/file3.ts
    4. 文件不存在, 尝试第二种替换"generated/*" => generated/folder2/file3
    5. 得到的是绝对路径, 将其与baseUrl结合, 得到projectRoot/generated/folder2/file3.ts
    6. 文件找到, 结束.

import后面的花括号

export分为两种, Named Export(有名导出)和Default Export(默认导出). 花括号是用于Named Export的.

Named Export

// module.ts
export function A() { ... };
export function B() { ... };

// app.ts
import { A, B as BB } from 'module.ts';

其中, 函数AB是Named Export模式, 导入时需要加花括号, 而且可以使用as改名.

Default Export

// module.ts
export default function C () { ... };

// app.ts
import myFunc from 'module';
// or
import { default as myFunc } from 'module';

函数Cdefault方式导出, 引入的时候不用加花括号, myFunc即为C.

其实default导出也是一种Named Export, 只不过它导出的变量被加了默认的名字default, 所以app.ts中的两句话效果一样.

export =import = require()

CommonJS 和 AMD 都有exports对象的概念, exports对象包含了所有导出的内容. 它们也都支持将exports对象替换为自己指定的一个对象/函数/变量等.

相应地, Typescript使用export =, 导出的内容可以是class, interface, namespace, function或者enum.

使用export =时必须相应地使用import module = require("module").

// module.ts
class A { ... }
export = A;
// app.ts
import A = requrie("module");

import * as X from "XXX"是什么意思

// pet.ts
export class Dog { ... }
export class Cat { ... }

// app.ts
import * as Pet from "./pet.ts";
let x = new Pet.Dog();

可以看到, import * as X from "XXX"的作用就是从"XXX"文件中, 引入所有导出的内容作为X的属性.

import X = require("XXX")作用相同.

ambient module declarations

var x = require VS import x from

在Node.js (CommonJS)中使用 var x = require("XXX"), 其中var也可以用const等修饰词替换. 与之配套的是module.exportsexports.

exports.A = function() {...}
module.exports.A = function() {...}
module.exports = { ... }

ES6采用import x from的形式, 与之配套的是export:

export function A() { ... }
export = { ... }

var x = requireimport x = require的区别?

我现在项目中常看到import x = require.

参考

  1. ECMAScript 6 modules: the final syntax
  2. Module Resolution
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,511评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,495评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,595评论 0 225
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,558评论 0 190
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,715评论 3 270
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,672评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,112评论 2 291
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,837评论 0 181
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,417评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,928评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,316评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,773评论 2 234
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,253评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,827评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,440评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,523评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,583评论 2 249