TypeScript 3.7 引入了對使用 JSDoc 語法從 JavaScript 生成 .d.ts 檔案的支援。
這意味著,無需將專案移植到 TypeScript,也不必在程式碼庫中維護 .d.ts 檔案,你就能享受到 TypeScript 驅動的編輯器帶來的開發體驗。TypeScript 支援大多數 JSDoc 標籤,你可以在此處檢視參考資料。
設定專案以生成 .d.ts 檔案
要在專案中新增 .d.ts 檔案的建立功能,你需要完成最多四個步驟:
- 將 TypeScript 新增到開發依賴(dev dependencies)中
- 新增一個
tsconfig.json來配置 TypeScript - 執行 TypeScript 編譯器,為 JS 檔案生成相應的 d.ts 檔案
- (可選)編輯你的 package.json 以引用這些型別
新增 TypeScript
你可以在我們的安裝頁面瞭解具體操作方法。
TSConfig
TSConfig 是一個 jsonc 檔案,用於配置編譯器標誌並宣告檔案的查詢位置。在這種情況下,你需要類似以下配置:
{// Change this to match your project"": ["src/**/*"],"": {// Tells TypeScript to read JS files, as// normally they are ignored as source files"": true,// Generate d.ts files"": true,// This compiler run should// only output d.ts files"": true,// Types should go into this directory.// Removing this would place the .d.ts files// next to the .js files"": "dist",// go to js file when using IDE functions like// "Go to Definition" in VSCode"": true}}
你可以在 tsconfig 參考中瞭解更多選項。除了使用 TSConfig 檔案外,也可以使用 CLI,其行為與命令列指令一致。
shnpx -p typescript tsc src/**/*.js --declaration --allowJs --emitDeclarationOnly --outDir types
執行編譯器
你可以在我們的安裝頁面瞭解如何操作。如果你的專案中有 .gitignore 檔案,請確保這些生成的檔案已被包含在你的包中。
編輯 package.json
TypeScript 在 package.json 中複製了模組的節點解析規則,並增加了一個查詢 .d.ts 檔案的步驟。簡而言之,解析過程會首先檢查可選的 types 欄位,然後是 "main" 欄位,最後會嘗試在根目錄下查詢 index.d.ts。
| Package.json | 預設 .d.ts 的位置 |
|---|---|
| 無 “types” 欄位 | 檢查 “main”,然後檢查 index.d.ts |
| “types”: “main.d.ts” | main.d.ts |
| “types”: “./dist/main.js” | ./dist/main.d.ts |
如果缺失,則使用 “main”
| Package.json | 預設 .d.ts 的位置 |
|---|---|
| 無 “main” 欄位 | index.d.ts |
| “main”:“index.js” | index.d.ts |
| “main”:“./dist/index.js” | ./dist/index.d.ts |