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 ="..."/>指令的文件排除在外。

相關文章
相關標籤/搜索