Typescript:为用 TS 编写的 UMD 模块创建声明

mic*_*elT 5 typescript webpack typescript-declarations

我在 TS 中写了一个小库用于学习目的。我正在使用 webpack 从我的打字稿创建 JS UMD 模块。

我的项目结构如下所示:

|-dist
    |-js
        |-my-lib.min.js    // Minified library as UMD module
|-src
    |-ts
        |-types
        |-interfaces
        |-utils
        |-components
            |-button.ts
            |-textField.ts
            |-dropdownMenu.ts
        |-my-lib.ts    // Source file for UMD lib
Run Code Online (Sandbox Code Playgroud)

my-lib.ts文件:

import {Button} from './components/button';
import {TextField} from './components/textField';
import {DropdownMenu} from './components/dropdownMenu';

export {
    Button,
    TextField,
    DropdownMenu,
}
Run Code Online (Sandbox Code Playgroud)

因此,当在 HTML 中包含my-lib.min.jsvia时src,我可以使用我的组件,例如:(UMD 模块以 webpack 命名myLib)。

const username = new myLib.TextField();
Run Code Online (Sandbox Code Playgroud)

现在我想在新的 ts 项目中使用我的库。我不希望交付 TS 文件,而只想交付声明。这样我就可以像使用 JS UMD 模块一样使用我的 ts lib,例如:

const username : myLib.TextField = new myLib.TextField();
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现这个目标?

  1. 是否可以自动创建声明文件?
  2. 如果没有,我如何手动创建声明文件?它的结构如何?

我试过tsc --declaration src\ts\my-lib.ts。然后my-lib.d.ts创建了一个文件,同时还创建了所有导入组件的声明文件,sobuttond.d.ts和.textfield.d.tsdropdownMenu.d.ts

另外,我的声明文件my-lib.ts看起来与原始文件非常相似(因为它都是关于导入/导出,没有类型或函数声明)。所以我不认为这个文件对我有帮助。

我的.tsconfig文件:

{
    "compilerOptions": {
        "forceConsistentCasingInFileNames": true,
        "noImplicitReturns": true,
        "strict": true,
        "noUnusedLocals": true,
        "target": "es5",
        "sourceMap": true,
        "declaration": true,
        "emitDeclarationOnly": true,
    },
    "lib": [
        "umd"
    ],
}
Run Code Online (Sandbox Code Playgroud)

小智 1

正如评论之一所建议的,此问题的可能解决方案可以是:dts-bundle-generator。它接受打字稿代码并将其捆绑到一个文件中,如果与--umd-module-name标志一起使用,它还会添加 umd 命名空间。 https://github.com/timocov/dts-bundle-generator