簡體   English   中英

如何創建一個`d.ts`文件來導入一個非模塊的外部npm庫

[英]how to create a `d.ts` file to import an external npm lib that is not a module

我想使用不是作為模塊編寫的npm lib

npm install "js-marker-clusterer" --save

這將安裝我想要的JS文件:

./node_modules/js-marker-clusterer/src/markerclusterer.js

// this is the Class I want to export/import
function MarkerClusterer(map, opt_markers, opt_options) {
  // ...
}

我想在我的TS文件中擴展和使用此類。 根據TS文檔,我可以聲明一個shorthand ambient module來執行此操作,但我不確定將不同文件放在何處。

速記環境模塊

如果您不想在使用新模塊之前花時間寫出聲明,則可以使用速記聲明快速入門。

declarations.d.ts (我在哪里放這個文件?)

 /// <reference path="node.d.ts"/> declare module "hot-new-module"; 

從速記模塊導入的所有內容都將具有任何類型。

 import x, {y} from "hot-new-module"; x(y); 

現在我有以下內容,但這不正確:

./src/app/shared/my-marker-clusterer.d.ts

/// <reference path="/node_modules/js-marker-clusterer/src/markerclusterer.js" />
// ERROR: typescript says *.js is an unsupported extension

declare module "js-marker-clusterer" {
  export class MarkerClusterer {
    constructor(map: any, opt_markers?: any, opt_options?: any);
    map_: any;
    markers_: any[];
    clusters_: any[];
    ready_: boolean;
    addMarkers(markers: any[], opt_nodraw: boolean) : void;
  }
}

/src/app/shared/my-marker-clusterer.ts

/// <reference path="./my-marker-clusterer.d.ts" />
import { MarkerClusterer } from 'js-marker-clusterer';

declare var google;

export class MyMarkerClusterer extends MarkerClusterer {
  constructor(map: any, opt_markers?: any, opt_options?: any) {
    super(map, opt_markers, opt_options);
  }

  addMarkers(markers, opt_nodraw) {
    super.addMarkers(markers, opt_nodraw)
    this.triggerClustersChanged()
  }
  triggerClustersChanged(){
    google.maps.event.trigger(this.map_, 'clustersChanged', this.clusters_);
  }
}

我正在使用rollupjs所以es2015模塊首選

好吧,我會被淹沒,我上面發布的代碼實際上是有用的。 我在下面得到了TS TS6054錯誤,但它仍然有效。

1 /// <reference path="/node_modules/js-marker-clusterer/src/markerclusterer.js" />
src/app/shared/my-marker-clusterer.d.ts(1,1): error TS6054: File '/node_modules/js-marker-clusterer/src/markerclusterer.js' has unsupported extension. The only supported extensions are '.ts', '.tsx', '.d.ts'.

我必須手動編輯JS文件並export

export function MarkerClusterer(map, opt_markers, opt_options) {
   // ...
}

有沒有一種方法可以在不編輯原始JS文件的情況下做同樣的事情?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM