從 .js 檔案建立 .d.ts 檔案

在 TypeScript 3.7 中,TypeScript 新增了使用 JSDoc 語法從 JavaScript 產生 .d.ts 檔案的支援。

此設定表示您可以在不將專案移植到 TypeScript 或在您的程式碼庫中維護 .d.ts 檔案的情況下,擁有由 TypeScript 提供技術支援的編輯器體驗。TypeScript 支援大部分 JSDoc 標籤,您可以在此處找到參考。

設定專案以發射 .d.ts 檔案

若要新增在專案中建立 .d.ts 檔案,您需要執行最多四個步驟

  • 將 TypeScript 新增至您的開發相依性
  • 新增 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
// 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
}
}

您可以在 tsconfig 參考 中瞭解更多選項。使用 TSConfig 檔案的替代方案是 CLI,這與 CLI 命令的行為相同。

sh
npx -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

提示

如果您想為 .d.ts 檔案撰寫測試,請嘗試 tsd

TypeScript 文件是一個開放原始碼專案。透過 傳送 Pull Request ❤ 來協助我們改善這些頁面。

此頁面的貢獻者
OTOrta Therox (16)
SG宋高 (1)
JB傑克·貝茨 (1)
SW史塔福·威廉斯 (1)
JS賈米·蘇歐馬萊寧 (1)
2+

最後更新:2024 年 3 月 21 日