【问题标题】:How to import jQuery to Angular2 TypeScript projects?如何将 jQuery 导入 Angular2 TypeScript 项目?
【发布时间】:2017-01-23 12:28:47
【问题描述】:

我想在 Angular2 指令中包装一些 jQuery 代码。

我使用以下命令将用于 Typings 的 jQuery 库安装到我的项目中:

typings install dt~jquery --save --global

所以现在我的项目目录中有typings/global 文件夹下的jquery 文件夹。此外,我的typings.json 文件中添加了以下新行:

{
    "globalDependencies": {
        "core-js": "registry:dt/core-js#0.0.0+20160602141332",
        "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
        "node": "registry:dt/node#6.0.0+20160807145350",
        "jquery": "registry:dt/jquery#1.10.0+20160908203239"
    }
}

我开始编写一个新的 Angular2 指令(我导入到 app-module 文件中),但我不知道如何正确导入 jQuery 库。这是我的源文件:

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

@Directive({
    selector: "my-first-directive"
})

export class MyFirstDirective {
    constructor() {
        $(document).ready(function () {
            alert("Hello World");
        });
    }
}

但我不能使用 $jQuery。下一步是什么?

【问题讨论】:

  • angular 已经提供了 jquery 的基本功能,而不是导入 jquery,因为它会导致长期的问题
  • 怎么用?例如,我会使用.dropdown() 方法...
  • 我不知道具体的功能。
  • 好的,无论如何我如何使用内置的 jQuery 库?
  • .dropdown() 不是 jquery 的函数。你在使用 bootstrap.js 吗?如果你正在使用它,那么你必须使用 jquery 或者只是切换到 ng-bootstrap,这是由 Angular 团队搜索 google 为 Angular 编写的引导程序。

标签: jquery angular typescript angular2-directives typescript-typings


【解决方案1】:

第 1 步:在您的项目中获取 jquery

npm install jquery

第 2 步:为 jquery 添加类型

npm install -D @types/jquery

第 3 步:在您的组件中使用它!

import * as $ from 'jquery';

准备使用 $!

【讨论】:

  • 是,但没有智能感知;(
  • @SharpNoiZy 我做到了,我有智能感知。但是,您必须将 jquery 添加到 tsconfig.json 中的类型数组中。
【解决方案2】:

如果您使用的是“@angular/cli”,请安装:

npm install jquery --save

第二步安装:

install: npm install @types/jquery --save-dev

并在根目录的“angular-cli.json”中找到您的文件名,并添加如下内容:

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

现在它可以工作了。

【讨论】:

  • 您还必须确保导入到组件中,使用:import * as $ from "jquery";
  • 显然不需要.. 如果您使用骨干网,您可能需要import * as $ from 'backbone';
【解决方案3】:

jQuery.service.ts

 import { OpaqueToken } from '@angular/core'
export let JQ_TOKEN = new OpaqueToken('jQuery');

index.ts`

export * from './jQuery.service';

app.module.ts

declare let jQuery : Object;

@NgModule({
  providers: [
    { provide: TOASTR_TOKEN, useValue: toastr },
    { provide: JQ_TOKEN, useValue: jQuery },
})
export class AppModule { }

如何在组件中使用Jquery

   import { Component, Input, ViewChild, ElementRef, Inject } from '@angular/core'
import { JQ_TOKEN } from './jQuery.service'

@Component({
  selector: 'simple-modal',
  template: `
  <div id="{{elementId}}" #modalcontainer class="modal fade" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
          <h4 class="modal-title">{{title}}</h4>
        </div>
        <div class="modal-body" (click)="closeModal()">
          <ng-content></ng-content>
        </div>
      </div>
    </div>
  </div>
  `,
  styles: [`
    .modal-body { height: 250px; overflow-y: scroll; }
  `]
})
export class SimpleModalComponent {
  @Input() title: string;
  @Input() elementId: string;
  @Input() closeOnBodyClick: string;
  @ViewChild('modalcontainer') containerEl: ElementRef;

  constructor(@Inject(JQ_TOKEN) private $: any) {}

  closeModal() {
    if(this.closeOnBodyClick.toLocaleLowerCase() === "true") {
      this.$(this.containerEl.nativeElement).modal('hide');
    }
  }
}

【讨论】:

  • OpaqueToken 已被弃用,但您可以简单地使用 InjectionToken 更改它,如此处所述thecodegarden.net/…
【解决方案4】:

您还可以在 index.html 的 head 部分中的普通 script 标记中加载您的 jQuery Javascript 文件。

<html>
    <head>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" />
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.js" />

        ...
    </head>
    ...

然后在你需要它的组件或指令中,只需声明 jQuery 所需的 $ 变量,因为你不会有你需要的所有插件的类型:

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

declare var $: any;

@Directive({
    selector: "my-first-directive"
})

export class MyFirstDirective {
    constructor() {
        $(document).ready(function () {
            alert("Hello World");
        });
    }
}

【讨论】:

  • 我应该在systemjs.config.js} 文件中写入以下行吗? 'jquery': 'typings/global/jquery/index.d.ts'
  • 不,不需要在 SystemJS 配置中写任何东西。只需将&lt;script&gt; 标记添加到您的index.html,您将在其中加载jquery.js。然后在需要的地方添加对组件或指令的引用。
  • 抱歉,我不知道它是如何工作的。你能给我一个例子或一些代码吗?
  • 这是老派的做法。
  • 不会撒谎 - 这个版本的使用外部 JS 文件将为您省去很多使用 SystemJS 或任何打包工具的麻烦。
【解决方案5】:

您应该有一个指向您的 jquery 输入文件的 typings.json。那么:

systemjs.config(jquery的通知地图设置)

System.config({
    defaultJSExtensions: true,
    paths: {
        // paths serve as alias
        'npm:': 'node_modules/'
    },
    map: {
        'app':  'app',
        jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js',
        material: 'npm:material-design-lite/dist/material.min.js',

        // angular bundles
        '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
        ....
    },
    packages: {
        app: { main: 'main', format: 'register', defaultExtension: 'js' },
        'rxjs': { defaultExtension: 'js' }
    },
});

在组件中:

import $ from 'jquery';

然后像往常一样使用 $。

【讨论】:

  • 所以我不需要用 tyipings 安装 jQuery 吗?我应该在systemjs.config.js 文件的地图对象中写下什么作为路径?
  • 如果你要使用“import $ from 'jquery';”,你需要输入。如果你不需要声明一个“任何”类型的'$'变量,否则打字稿会抱怨错误的类型
  • 如果我使用scripts html 标签导入,我不能使用 jQuery 在我的 Angular2 指令/组件中编写代码。
  • 不要使用脚本标签导入。让 typescript 和 systemjs 为你做这件事,并以 angular 2 的方式做。
  • 为什么import * as $ from 'jquery' 有效?无论如何,即使使用dropdown jQuery 插件,如何使它工作?
【解决方案6】:

我认为在 Angular 2 中使用 jquery 应该不是问题。如果正确安装了 jquery 的类型和依赖项,那么在 Angular 2 中使用 jquery 应该不是问题。

通过正确安装,我能够在我的 angular 2 项目中使用 jquery。通过正确安装,我的意思是安装 jquery 类型以便在打字稿中识别它。

之后,我可以通过以下方式使用 jquery:

jQuery(document).ready({
    ()=>{
        alert("Hello!");
    };
});

【讨论】:

    【解决方案7】:

    这是个老问题,已经有一些答案了。然而,现有的答案过于复杂(来自 user1089766 的答案包含许多不必要的东西)。希望这可以帮助新人。

    &lt;script src="http://code.jquery.com/jquery-3.2.1.min.js"&gt;&lt;/script&gt; 添加到您的index.html 文件中。

    创建 jQuery.Service.ts:

    import {InjectionToken} from "@angular/core";
    export let jQueryToken = new InjectionToken('jQuery'); 
    

    在您的模块文件中,将此 jQueryToken 添加到提供程序:

    providers:[
    {
        provide: jQueryToken,
        useValue: jQuery
    
    }] 
    

    现在@Inject(jQueryToken) 可以使用了。假设您想在组件名称 ExperimentComponent 内部使用:

    import {Component, Inject, OnInit} from '@angular/core';
    import {jQueryToken} from "./common/jquery.service";
    
    @Component({
        selector: 'app-experiment',
        templateUrl: './experiment.component.html',
        styleUrls: ['./experiment.component.css']
    })
    export class ExperimentComponent implements OnInit {
    
        constructor(@Inject(jQueryToken) private $: any) {
            $(document).ready(function () {
                alert(' jQuery is working');
            });
        }
    
        ngOnInit() {
        }
    
    }
    

    每当您打开 ExperimentComponent 时,警报函数都会调用并弹出消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 2017-10-02
      • 2019-07-28
      相关资源
      最近更新 更多