【问题标题】:how to create a `d.ts` file to import an external npm lib that is not a module如何创建 `d.ts` 文件以导入不是模块的外部 npm lib
【发布时间】:2017-02-09 09:53:54
【问题描述】:

我想使用一个不写成模块的 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";

来自速记模块的所有导入都将具有 any 类型。

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 模块

【问题讨论】:

    标签: javascript typescript rollupjs


    【解决方案1】:

    好吧,我会被诅咒的,我上面发布的代码确实有效。我得到了下面的 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 文件的情况下做同样的事情?

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 2017-07-08
      • 2017-04-14
      • 2016-12-08
      相关资源
      最近更新 更多