网站搜索

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


我刚刚发布了一个用 TypeScript 编写的 npm 包。目前我在使用 TypeScript(Webpack 和 VSCode)时遇到了很多关于类型定义识别的问题。到目前为止唯一有效的解决方案是创建一个包含定义的文件夹在 node_modules/@types 中。

简要说明,这是我的软件包设置:

tsconfig.json

{
    "compilerOptions": {
        ...
        "outDir": "./lib/",
        "declaration": true,
        "declarationDir": "./src/",
    }
}

package.json

{
    ...
    "types": "./index.d.ts",
}

index.d.ts

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

src/nano-data-binding.d.ts

我把它保存在 /src 中,因为它是自动生成的,我无法控制导入的路径。另外,如果我尝试只使用 declare var ... 而不使用 import export 语句,就可以获得一个脚本而不是模块。

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 包

{
    ...
    "types": "lib/nano-data-binding.d.ts",
    "typings": "lib/nano-data-binding.d.ts",
    "typescript": {
        "definition": "lib/nano-data-binding.d.ts"
    },
}

tsconfig.json - 本地项目

{
    ...
    "files": [
        "node_modules/nano-data-binding/lib/nano-data-binding.d.ts"
    ]
}

答案#1

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

答案#2

终于找到了有效的方法。看起来在根目录使用 index.d.ts 就足够了,或者在包的 package.json 中指定一个自定义路径。

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

index.d.ts

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[];
}

然后它的导入方式

main.ts

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