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