简体   繁体   English

make.d.ts 用于项目可用的外部库文件

[英]make .d.ts for external library file available for project

I have a closed-source plain JS library that will be included via a <script> tag pointing to a CDN.我有一个闭源纯 JS 库,它将通过指向 CDN 的<script>标记包含在内。 I would like to author my own type definition file for this library so I can reference a global object that the library provides once loaded into the HTML page.我想为这个库编写自己的类型定义文件,这样我就可以引用该库在加载到 HTML 页面后提供的全局 object。

So far I am having trouble getting my IDE to show me that it recognizes the.d.ts file.到目前为止,我无法让我的 IDE 向我展示它可以识别 .d.ts 文件。

I have the following project structure:我有以下项目结构:

project-folder/
 - tsconfig.json
 - src/
definitions/
- mylibrary.d.ts

In tsconfig I have the following:在 tsconfig 我有以下内容:

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM"],
    "moduleResolution": "Node",
    "strict": true,
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "typeRoots": ["../definitions/"]
  },
  "include": ["./src"]
}

In mylibrary.d.ts I have the following:在 mylibrary.d.ts 我有以下内容:

interface example {
  hello: boolean;
}

declare namespace MyLibraryObject {
    const testing: string; 
    function foo(bar: string): void;
}

Then in main.ts I attempt to use any of the types defined in the d.ts file such as:然后在 main.ts 我尝试使用 d.ts 文件中定义的任何类型,例如:

const test: example = { hello: true };

console.log(MyLibraryObject.testing);
MyLibaryObject.foo();

But TS cannot find the definitions for these, as seen here:但是 TS 找不到这些的定义,如下所示:

vscode中TS错误截图

What can I do to resolve this?我能做些什么来解决这个问题?

I figured it out, the solution was to expand the set of "included" paths in the tsconfig file.我想通了,解决方案是扩展 tsconfig 文件中的“包含”路径集。

{
  "compilerOptions": {
    ...
    "typeRoots": ["../definitions/"]
  },
  "include": ["./src", "../definitions/"]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM