简体   繁体   English

如何为全局第三方库导入 TypeScript 模块定义

[英]How to import a TypeScript module definition for a global third-party library

I am using a third-party Javascript library that has to be imported directly via a <script> tag in my index.html file.我正在使用第三方 Javascript 库,该库必须通过 index.html 文件中的<script>标签直接导入。 As the library is in my public/ folder, Typescript (v3.8.3) is able to find it.由于库位于我的public/文件夹中,因此 Typescript (v3.8.3) 能够找到它。

The library looks like this:图书馆看起来像这样:

var MyLib = {x: ..., y: ... z:...}
MyLib.SomeFunc = ...
MyLib.SomeOtherFunc = ...

When I use MyLib in my Typescript project (as a global, no import statement), Typescript recognizes MyLib as having the properties X, YZ , but not SomeFunc and SomeOtherFunc .当我在我的 Typescript 项目中使用MyLib时(作为一个全局的,没有import语句),Typescript 将 MyLib 识别为具有属性X, YZ ,但没有SomeFuncSomeOtherFunc

To fix this, there exists a typings file, mylib.d.ts .为了解决这个问题,存在一个类型文件mylib.d.ts

It looks like this:它看起来像这样:

export = MyLib;

declare module MyLib {
  function SomeFunc ...;
  ...
}

I added mylib.d.ts to my src root, where my other *.d.ts files are.我将mylib.d.ts添加到我的 src 根目录,我的其他*.d.ts文件所在的位置。

However, Typescript does not pick this up.但是,Typescript没有选择这一点。 It sticks to the inferences it has made by reading the MyLib.js file directly.它坚持通过直接读取MyLib.js文件所做的推断。

How can I get Typescript to read these definitions?如何让 Typescript 阅读这些定义?

What I have tried:我尝试过的:

  • /// <reference types="../myLib" . /// <reference types="../myLib" . Typescript still uses the auto-generated types from the actual myLib.js file Typescript 仍然使用来自实际myLib.js文件的自动生成类型
  • import "../myLib"; . . Doesn't work because it's just a typing file, not a module.不起作用,因为它只是一个打字文件,而不是一个模块。
  • import type MyLib from "../myLib"; . . This seems to not be valid Typescript yet, although it seemed like it was going to be in v3.8.这似乎还不是有效的 Typescript,尽管它似乎将出现在 v3.8 中。 I'm not sure if that's correct anyway, because MyLib is a namespace, not a type.我不确定这是否正确,因为 MyLib 是一个命名空间,而不是一个类型。

If typings are in npm then include @types/mylib.d.ts into devDependencies of your package.json file then compiler will not have an issue with:如果类型在 npm 中,则将 @types/mylib.d.ts 包含到 package.json 文件的 devDependencies 中,那么编译器不会有以下问题:

import '../myLib';

Otherwise add folder where *.d.ts files are located into compilerOptions / typeRoots array located in tsconfig.json.否则,将 *.d.ts 文件所在的文件夹添加到位于 tsconfig.json 中的 compilerOptions / typeRoots 数组中。 It should already have "node_modules/@types".它应该已经有“node_modules/@types”。 For example:例如:

    "typeRoots": [
        "myLibTypesFolder",
        "node_modules/@types"
    ],

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

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