【问题标题】:Typescript: Create declarations for UMD module which is written in TSTypescript:为用 TS 编写的 UMD 模块创建声明
【发布时间】:2021-10-16 10:48:40
【问题描述】:

我在 TS 中写了一个小库用于学习目的。我正在使用 webpack 从我的 typescript 创建一个 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

my-lib.ts文件:

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

export {
    Button,
    TextField,
    DropdownMenu,
}

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

const username = new myLib.TextField();

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

const username : myLib.TextField = new myLib.TextField();

我怎样才能做到这一点?

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

我试过tsc --declaration src\ts\my-lib.ts。然后创建了一个my-lib.d.ts 文件以及所有导入组件的声明文件,因此buttond.d.tstextfield.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"
    ],
}

【问题讨论】:

  • 您找到解决此问题的方法了吗?
  • 是的,我现在正在使用dts-bundle-generator。这个包以我的my-lib.ts 文件为目标,并为所有包含的依赖项创建一个.d.ts 文件。但我必须添加以下几行才能让它按我的意愿工作(作为全局库,在我的 html 页面中包含为<script> 标记):export as namespace myLib; export { }; declare global { var myLib: typeof myLib; }

标签: typescript webpack typescript-declarations


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多