[英]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.