如何为 umd 库创建 TypeScript 定义文件 (d.ts)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40155100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:56:34  来源:igfitidea点击:

How to create TypeScript definition file (d.ts) for umd library

typescriptwebpackdefinitelytypedumd

提问by duodvk

I am working on the library surveyjs

我正在研究图书馆调查js

It uses gulp+webpackto build umd bundle.

它使用gulp+webpack来构建 umd 包。

I want to create the type definition bundle (or may be just multiple d.ts files) for using in typescript projects. I would like to have something like that:

我想创建用于打字稿项目的类型定义包(或者可能只是多个 d.ts 文件)。我想要这样的东西:

import * as Survey from 'surveyjs';

All contens for Survey.* is described here: https://github.com/dmitrykurmanov/surveyjs/blob/master/src/entries/ko.ts

此处描述了 Survey.* 的所有内容:https: //github.com/dmitrykurmanov/surveyjs/blob/master/src/entries/ko.ts

I have tried to use: github.com/SitePen/dts-generatorand github.com/TypeStrong/dts-bundlebut whithout success, could somebody please show me the right direction?

我曾尝试使用:github.com/SitePen/dts-generatorgithub.com/TypeStrong/dts-bundle但没有成功,有人可以告诉我正确的方向吗?

采纳答案by toskv

You can ask tscto generate the declaration files for your code by adding the declarationflag in tsconfig.json.

您可以通过在tsconfig.json 中添加声明标志来要求tsc为您的代码生成声明文件。

In your case it would be:

在您的情况下,它将是:

{
  "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"
  ]
}

回答by Aaron Schmid

As toskv mentioned you can use tscto generate the .d.ts files. Problem there is that the compiler creates multiple declaration files, one for each of your .ts file. I had the same problem with another projected I worked on. I soved it by creating a small plugin for webpack which mergesthe .d.tsfiles generated by tsc.

正如 toskv 提到的,您可以使用tsc生成 .d.ts 文件。问题是编译器创建了多个声明文件,每个 .ts 文件一个。我在另一个项目中遇到了同样的问题。我通过为 webpack 创建一个小插件来解决它,该插件合并了tsc 生成的.d.ts文件。

You can check it out on here: https://www.npmjs.com/package/typescript-declaration-webpack-plugin

你可以在这里查看:https: //www.npmjs.com/package/typescript-declaration-webpack-plugin