Angular4 - 引入第三方jquery

原文出处:https://blog.csdn.net/it_rod/article/details/78848311

由于最近在Angular4中引入jquery的方式,先是使用了一种普通的方式,在对应的文件中import jquery,可以实现功能。只是后来自己想着怎么把$符号变成一种全局可识别的变量,所以花了一些时间去研究它。

1. import * as $ from 'jquery'

(1) 将第三方类库安装到本地

npm install jquery --save

(2)将库引入到当前的项目中去

修改.angular-cli.json的"scripts"

 
  1. "scripts": [

  2. "../node_modules/jquery/dist/jquery.min.js"

  3. ],

(3)import * as $ from 'jquery';

修改app.component.ts

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

  2. import * as $ from 'jquery';

  3.  
  4. @Component({

  5. selector: 'app-root',

    扫描二维码关注公众号,回复: 2713996 查看本文章
  6. templateUrl: './app.component.html',

  7. styleUrls: ['./app.component.css']

  8. })

  9. export class AppComponent {

  10. title = 'app';

  11.  
  12. ngOnInit() {

  13. $("body").css("color", "blue");

  14. }

  15. }

2. npm install @types/jquery --save

当我想将$变成全局变量的时候,遇到了这个命令,但是仅仅这个命令还是不行的。

上面的(1)(2)步骤还是需要的,我直接从第三步将好了。

(3)npm install @types/jquery --save

现将app.component.ts中下面的code去掉,这样才具有说明性。

import * as $ from 'jquery';

然后启动项目,会发现报错ERROR in src/app/app.component.ts(12,4): error TS2304: Cannot find name '$'.

然后执行下面的命令

npm install @types/jquery --save

(4)修改src/typing.d.ts

 
  1. /* SystemJS module definition */

  2. declare var module: NodeModule;

  3. declare var $: any;

  4. declare var jQuery: any;

  5.  
  6. interface NodeModule {

  7. id: string;

  8. }

至此,我们可以直接使用$了,具体的原因,我去看过\node_modules\@types\jquery\index.d.ts,并且修改文件让其没有export,但是项目中仍然可以使用$。希望有了解这个原因的可以说明一下,不胜感激!

猜你喜欢

转载自blog.csdn.net/chelen_jak/article/details/81328299