Angular4 - 引入第三方jquery

本文详细介绍了如何在Angular项目中全局配置并使用jQuery,通过安装jQuery及其类型定义,修改项目配置,最终实现在整个项目范围内无需导入即可使用jQuery。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文出处:https://blog.youkuaiyun.com/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',

  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,但是项目中仍然可以使用$。希望有了解这个原因的可以说明一下,不胜感激!

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值