如何在 angular 4 中使用自定义 jquery 插件

How to use custom jquery plugins in angular 4

我正在尝试在 Angular 4 项目中使用名为 imgViewer2(https://github.com/waynegm/imgViewer2) 的 jquery 插件。

我安装了 npm 包并成功导入 jquery 并且使用得很好。 但是,当我尝试使用 $(element).imgViewer2(); 时,打字稿说找不到该功能。我无法正确导入插件。

这个插件的导入和使用方法是什么?

非常感谢。

compile errorwhen added code snippet

已解决

很可能是 Avaid 的第一个建议,

在 angular-cli.json.

中添加了 jquery 及其对脚本数组的插件引用
...
scripts: [
    "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/imgViewer2/imgViewer2.min.js"
],
...

然后只需将以下行添加到您的 .ts 文件中即可使用 jQuery。

declare var $: JQuery;

现在 $ 带有插件添加的功能和属性。我不知道是否有更好的方法来做到这一点,但知道这对我来说是无痛的。谢谢。

这是因为 jquery 的类型不包含对 imgViewer2 的任何引用,您可以通过包含此位在组件源中对其进行修补:

declare var $: JQuery;

declare global {
  interface JQuery {
    (selector: string): JQuery;
    imgViewer2(): JQuery;
  }
}

这将让打字稿知道可以调用 imgViewer2() 作为类型对象的方法 JQuery (我假设你已经定义了,因为你已经说过你正在使用jquery 在您的应用中)

将此代码添加到您要在全局级别调用 imgViewer2 的同一文件中。

编辑

要完成这个答案,为了在应用程序中正确使用 jquery,将其添加到文件 .angular-cli.json 中的 scripts 数组,因此:

scripts: [
  "../node_modules/jquery/dist/jquery.min.js"
]

然后在你的组件中使用上面的声明,这里是一个示例骨架组件:

import { Component } from '@angular/core';

declare var $: JQuery;

declare global {
  interface JQuery {
    (selector: string): JQuery;
    imgViewer2(): JQuery;
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    console.log($);
    $('div#myDiv').imgViewer2();
  }
}

编辑 2

或者,如果您安装 jquery 打字 npm i --save-dev @types/jquery 那么您可以使用稍微不同的策略,它的类型更强:

import { Component } from '@angular/core';
import 'jquery';

declare global {
  interface JQuery {
    imgViewer2(): JQuery;
  }
}

请注意,您现在必须 import 'jquery',而不必 declare var $...,而且您不必重复调用签名,因为它已经在打字库。

已解决

在 angular-cli.json.

中添加了 jquery 及其对脚本数组的插件引用
...
scripts: [
    "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/imgViewer2/imgViewer2.min.js"
],
...

然后只需将以下行添加到您的 .ts 文件中即可使用 jQuery。

declare var $: JQuery;

现在 $ 带有插件添加的功能和属性。 我不知道是否有更好的方法来做到这一点,但知道这对我来说是无痛的。谢谢