【发布时间】: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();
我怎样才能做到这一点?
- 是否可以自动创建声明文件?
- 如果没有,如何手动创建声明文件?它的结构如何?
我试过tsc --declaration src\ts\my-lib.ts。然后创建了一个my-lib.d.ts 文件以及所有导入组件的声明文件,因此buttond.d.ts、textfield.d.ts 和dropdownMenu.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