TypeScript基礎入門之模組解析(三)
繼續上文[ofollow,noindex">TypeScript基礎入門之模組解析(二) ]
跟蹤模組解析
如前所述,編譯器可以在解析模組時訪問當前資料夾之外的檔案。
在診斷模組未解析的原因或解析為錯誤定義時,這可能很難。
使用--traceResolution啟用編譯器模組解析度跟蹤可以深入瞭解模組解析過程中發生的情況。
假設我們有一個使用typescript模組的示例應用程式。
app.ts有一個匯入,比如import * as ts from "typescript"。
│tsconfig.json ├───node_modules │└───typescript │└───lib │typescript.d.ts └───src └───app.ts
使用--traceResolution呼叫編譯器
tsc --traceResolution
輸出結果如下:
======== 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'. ========
值得關注的事情
1. 匯入的名稱和位置
======== Resolving module 'typescript' from 'src/app.ts'. ========
2. 編譯器遵循的策略
Module resolution kind is not specified, using 'NodeJs'.
3. 從npm包載入型別
'package.json' has 'types' field './lib/typescript.d.ts' that references 'node_modules/typescript/lib/typescript.d.ts'.
4. 最後結果
======== 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 ="..."/> 指令的檔案排除在外。