為什麼聲明文件很重要
當您發佈以 TypeScript 編寫的 npm 套件時,使用者需要類型資訊來取得 IntelliSense 和編譯時檢查。如果沒有“.d.ts”文件,您的庫實際上會被鍵入為“any”,這從一開始就違背了使用 TypeScript 的目的。
聲明文件描述了導出的形狀,而無需運送實施來源。它們可以在消費者項目中實現樹搖動、文檔懸停提示和嚴格的類型檢查。
產生 .d.ts 文件
當「tsconfig.json」中的「declaration」設定為「true」時,TypeScript 編譯器會產生聲明檔。
{
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"emitDeclarationOnly": true,
"outDir": "./dist",
"rootDir": "./src"
}
}
| 選項 | 目的 |
|---|---|
宣告 | 與「.js」輸出一起發出「.d.ts」檔 |
聲明映射 | 生成聲明的來源映射(在編輯器中轉到定義) |
emitDeclarationOnly | 僅發出聲明,不發出 JS(當另一個工具處理捆綁時使用) |
outDir | JS 與 .d.ts 檔案的輸出目錄 |
運行建置:
@@@代碼區塊1@@@
輸出結構反映了您的“src/”佈局。檔案 src/index.ts 產生 dist/index.js 和 dist/index.d.ts。
Package.json 類型字段
「types」欄位(或其別名「typings」)指向條目宣告檔案。
{
"name": "my-library",
"main": "./dist/index.js",
"types": "./dist/index.d.ts"
}
對於雙 ESM/CJS 套件,「exports」欄位提供條件解析:
{
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"./subpath": {
"import": {
"types": "./dist/subpath.d.mts",
"default": "./dist/subpath.mjs"
},
"require": {
"types": "./dist/subpath.d.ts",
"default": "./dist/subpath.js"
}
}
}
}
這告訴 TypeScript 為“import”語句載入“index.d.mts”,為“require()”呼叫載入“index.d.ts”。
三斜線指令
在手寫的環境聲明中,使用三斜線指令來引用其他類型。
/// <reference types="node" />
/// <reference path="./custom-types.d.ts" />
export function readConfig(path: string): Buffer;
這些僅在“.d.ts”文件中有效,在實現“.ts”文件中無效。對於產生的聲明,請改為依賴普通的「import」語句。
在您的包裹中包含聲明
package.json 中的 files 欄位控制發佈到 npm 的內容:
{
"files": [
"dist",
"!dist/**/*.test.d.ts",
"README.md",
"LICENSE"
]
}
始終排除測試聲明文件和來源“.ts”文件,除非您打算發布它們。
測試你的聲明
在發布之前,請先驗證消費者是否可以正確解析您的類型。
# Create a test project
mkdir test-consumer && cd test-consumer
npm init -y
npm link ../my-library
import { MyType } from "my-library";
const x: MyType = { /* ... */ };
在測試項目中執行“npx tsc –noEmit”。如果編譯沒有錯誤,則您的聲明是正確的。
常見陷阱
| 問題 | 解決方案 |
|---|---|
.js 檔案缺少 .d.ts | 在 tsconfig |
| 消費者看到的是「any」而不是正確的類型 | 驗證「types」欄位指向正確的條目 |
| 雙 ESM/CJS 類型無法解決 | 將“exports”與單獨的“types”條件一起使用 |
| 宣告來源圖已損壞 | 新增 declarationMap: true |
| 公共 API 中的私有類型外洩 | 使用 _ 前綴內部類型或使用 @internal JSDoc 標籤 |
總結
正確產生和發布聲明文件可確保您的 TypeScript 庫提供一流的開發人員體驗。在 tsconfig 中配置 declaration: true,在 package.json 中設定 types 字段,對雙模組包使用 exports,並在發布之前始終針對消費者項目測試您的聲明。

