[英]Typescript does not resolve definition file for npm package
我刚刚发布了一个用typescript编写的npm 包 。 目前,我在使用typescript(webback和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 /纳米数据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"
]
}
在你的package.json
你需要将types
字段重命名为typings
。是的,这里不需要三重斜杠指令
终于找到了有用的东西。 看起来在根级别使用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
您遇到的问题是由于您的tsconfig.json尝试显式包含键入文件。 当你在package.json中指定types
或typings
字段时,会自动加载npm package typings文件。
当您删除tsconfig.json中的files
数组中的条目时,它应该可以正常工作。
您找到的解决方案(添加declare module 'nano-data-binding' { }
)是一种解决方案,用于为某些包创建自定义类型而无需打字。
为了更具技术性,当一个打字文件(d.ts)不包含顶级导入导出语句时,它是一个环境脚本文件,它是全局范围的。 这就是为什么你需要declare module '...'
来表明你正在为哪个模块添加输入。
如果我的网站已经在使用moment.min.js,您通常会在如何使用Moment.js TypeScript定义文件中使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.