webpack - 如何為 UMD 函式庫建立 TypeScript 定義檔(.d.ts)
我正在使用程式庫 surveyjs
它使用 gulp+webpack 來構建 UMD 包。
我想為在 TypeScript 專案中使用創建類型定義包(或者可能只是多個 d.ts 文件)。我希望有像這樣的東西:
import * as Survey from 'surveyjs';
所有關於 Survey.* 的內容都在這裡描述:https://github.com/dmitrykurmanov/surveyjs/blob/master/src/entries/ko.ts
我已經嘗試使用:github.com/SitePen/dts-generator 和 github.com/TypeStrong/dts-bundle,但沒有成功,是否有人可以指引我正確的方向?
答案#1
你可以透過在 tsconfig.json 中加入 declaration 標誌,要求 tsc 為你的程式碼生成宣告檔。
在你的情況下,它將是:
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"sourceMap": true,
"noImplicitAny": false,
"jsx": "react",
"declaration": true
},
// "filesGlob": [
// "typings/index.d.ts"
// ], // TODO
"include": [
"typings/index.d.ts",
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
答案#2
正如 toskv 提到的,你可以使用 tsc 來生成 .d.ts 文件。問題是編譯器會為你的每個 .ts 文件創建多個聲明文件。我在另一個項目中也遇到過同樣的問題。我是通過為 webpack 創建一個小插件來解決的,該插件可以 合併 tsc 生成的 .d.ts 文件。
你可以在這裡查看: https://www.npmjs.com/package/typescript-declaration-webpack-plugin
