Typescript无法解析npm包的定义文件

Typescript does not resolve definition file for npm package

我刚刚发布了一个用打字稿编写的npm包。 目前,我很难通过打字稿(Webback和vscode)识别该定义。 到目前为止,唯一有效的解决方案是使用node_modules/@types中的定义创建一个文件夹

简而言之,这是我的软件包设置:

tsconfig.json

1
2
3
4
5
6
7
8
{
   "compilerOptions": {
        ...
       "outDir":"./lib/",
       "declaration": true,
       "declarationDir":"./src/",
    }
}

package.json

1
2
3
4
{
    ...
   "types":"./index.d.ts",
}

索引

1
/// <reference path="src/nano-data-binding.d.ts" />

src / nano-data-binding.d.ts

我将其保留在/src中,因为它是自动生成的,并且我无法控制导入的路径。 另外,如果我尝试仅使用declare var ...而不使用import export语句来获取脚本而不是模块。

1
2
3
import { StringOrHTMLElement } from './interfaces/nano-data-binding';
export declare function nanoBind(parent: HTMLElement, ...selectors: StringOrHTMLElement[]): HTMLElement[];
export declare function nanoBindAll(parent: HTMLElement, ...selectors: string[]): HTMLElement[];

随时安装该软件包,也许这只是某个地方的一个小错误。 基本上,我想将nanoBind()nanoBindAll()声明为全局变量。

编辑

我尝试过的其他东西。 什么都没有。

package.json-Npm软件包

1
2
3
4
5
6
7
8
{
    ...
   "types":"lib/nano-data-binding.d.ts",
   "typings":"lib/nano-data-binding.d.ts",
   "typescript": {
       "definition":"lib/nano-data-binding.d.ts"
    },
}

tsconfig.json-本地项目

1
2
3
4
5
6
{
    ...
   "files": [
       "node_modules/nano-data-binding/lib/nano-data-binding.d.ts"
    ]
}


您遇到的问题是由于tsconfig.json试图显式包括键入文件。
当您在package.json中指定typestypings字段时,将自动加载npm软件包类型文件。

当您删除tsconfig.json中files数组中的条目时,它应该可以正常工作。

您找到的解决方案(添加declare module 'nano-data-binding' { })是一种为某些软件包创建自定义类型而无需键入的解决方案。

稍微讲一点技术,当键入文件(d.ts)不包含顶层import export语句时,它是一个环境脚本文件,并且是全局范围的。这就是为什么您需要declare module '...'来指示要为其添加键入内容的模块。

如果我的站点已经在使用moment.min.js,则通常按照如何使用Moment.js TypeScript定义文件中的说明使用它们?


终于找到了行之有效的东西。在根级别使用index.d.ts或在包的package.json中指定自定义路由似乎就足够了。

问题出在我的定义上。它需要声明一个模块。

索引

1
2
3
4
5
6
7
8
type StringOrHTMLElement = string | HTMLElement
declare var nanoBind: (parent: HTMLElement, ...selectors: StringOrHTMLElement[]) => HTMLElement[];
declare var nanoBindAll: (parent: HTMLElement, ...selectors: string[]) => HTMLElement[];

declare module 'nano-data-binding' {
    export var nanoBind: (parent: HTMLElement, ...selectors: any[]) => HTMLElement[];
    export var nanoBindAll: (parent: HTMLElement, ...selectors: string[]) => HTMLElement[];
}

而且比导入的方式

主要

1
2
import * as ndb from 'nano-data-binding' // Imports script and definition
require('nano-data-binding') // Ignores definition


在您的package.json中,您需要将types字段重命名为typings
是的,这里不需要三斜杠指令