TypeScript基础入门之模块解析(三)

转发 TypeScript基础入门之模块解析(三)node

继续上文[TypeScript基础入门之模块解析(二)]typescript

跟踪模块解析

如前所述,编译器能够在解析模块时访问当前文件夹以外的文件。
在诊断模块未解析的缘由或解析为错误定义时,这可能很难。
使用--traceResolution启用编译器模块分辨率跟踪能够深刻了解模块解析过程当中发生的状况。npm

假设咱们有一个使用typescript模块的示例应用程序。
app.ts有一个导入,好比import * as ts from "typescript"。json

│   tsconfig.json
├───node_modules
│   └───typescript
│       └───lib
│               typescript.d.ts
└───src
    └───app.ts


使用--traceResolution调用编译器

tsc --traceResolution

输出结果以下:app

======== Resolving module 'typescript' from 'src/app.ts'. ========
Module resolution kind is not specified, using 'NodeJs'.
Loading module 'typescript' from 'node_modules' folder.
File 'src/node_modules/typescript.ts' does not exist.
File 'src/node_modules/typescript.tsx' does not exist.
File 'src/node_modules/typescript.d.ts' does not exist.
File 'src/node_modules/typescript/package.json' does not exist.
File 'node_modules/typescript.ts' does not exist.
File 'node_modules/typescript.tsx' does not exist.
File 'node_modules/typescript.d.ts' does not exist.
Found 'package.json' at 'node_modules/typescript/package.json'.
'package.json' has 'types' field './lib/typescript.d.ts' that references 'node_modules/typescript/lib/typescript.d.ts'.
File 'node_modules/typescript/lib/typescript.d.ts' exist - use it as a module resolution result.
======== Module name 'typescript' was successfully resolved to 'node_modules/typescript/lib/typescript.d.ts'. ========

值得关注的事情spa

1. 导入的名称和位置命令行

======== Resolving module 'typescript' from 'src/app.ts'. ========

2. 编译器遵循的策略code

Module resolution kind is not specified, using 'NodeJs'.

3. 从npm包加载类型blog

'package.json' has 'types' field './lib/typescript.d.ts' that references 'node_modules/typescript/lib/typescript.d.ts'.

4. 最后结果ip

======== Module name ‘typescript’ was successfully resolved to ‘node_modules/typescript/lib/typescript.d.ts’. ========

使用--noResolve

一般,编译器将在启动编译过程以前尝试解析全部模块导入。
每次成功解析导入到文件时,该文件都会添加到编译器稍后将处理的文件集中。

--noResolve编译器选项指示编译器不要将任何文件"add"到未在命令行上传递的编译中。
它仍将尝试将模块解析为文件,但若是未指定该文件,则不会包含该文件。

例如:

app.ts

import * as A from "moduleA" // OK, 'moduleA' passed on the command-line
import * as B from "moduleB" // Error TS2307: Cannot find module 'moduleB'.
tsc app.ts moduleA.ts --noResolve

使用--noResolve编译app.ts应该致使:
1. 正确查找在命令行上传递的moduleA。
2. 找不到未经过的moduleB时出错。

常见问题

为何排除列表中的模块仍然被编译器拾取?

tsconfig.json将文件夹转换为"project"。若是不指定任何"exclude"或"files"条目,则包含tsconfig.json及其全部子目录的文件夹中的全部文件都包含在编译中。
若是要排除某些文件使用"exclude",若是您但愿指定全部文件而不是让编译器查找它们,请使用"files"。

那是tsconfig.json自动包含。
这并无嵌入上面讨论的模块解析。
若是编译器将文件标识为模块导入的目标,则不管它是否在前面的步骤中被排除,它都将包含在编译中。

所以,要从编译中排除文件,您须要将其和全部具备import或/// <reference path ="..."/>指令的文件排除在外。

相关文章
相关标签/搜索