Angular6 + Typescript 项目中怎么引用包装到jquery里面的插件

Angular6 + Typescript项目中用到了一个包含到jquery里面的插件 fontIconPicker

https://github.com/fontIconPicker/fontIconPicker

https://codeb.it/fonticonpicker/

首先根据github上面的readme 安装 jquery 和 fonticonpicker

npm install jquery@1.12.4 @fonticonpicker/fonticonpicker --save

然后看到ES6中的使用方法

import jQuery from 'jquery';
import initFontIconPicker from '@fonticonpicker/fonticonpicker';

// Initiate the jQuery plugin
initFontIconPicker( jQuery );

jQuery( '.selector' ).fontIconPicker( {
    // Options
} );

在编译时, 首先会得到如下错误

ERROR in error TS2688: Cannot find type definition file for 'jquery'.

可以看到是 TSxxx 的错误,也就是说ts识别不到jquery;因此想到安装 @types/jquery

 npm install @types/jquery --save-dev

此时,如果你的tsconfig.json里面配置了"types"属性,那么你需要将jquery加入到列表里面,以供 全局使用。当然,如果你使用的是import导入jquery,不加也是没有关系的。但建议加上

// tsconfig.json

{
"compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": true, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "types": ["jquery", "node"], "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ] } }

然后再次启动项目 npm start,发现错误信息变了, 但依旧是TSxxx的error;

ERROR in src/app/components/dashboard/dashboard.component.ts(29,26): error TS2339: Property 'fontIconPicker' does not exist on type 'JQuery<HTMLElement>

也就是说,现在编译器可以识别到jquery了,但是在jquery方法里面找不到 fontIconPicker. 根据上面的原理,我们也可以知道是declaration的问题,我们需要declaration告诉ts编译器 fontIconPicker是jquery里面的方法。通常的写法如下(当然也需要看该方法的使用)

//   src/typings.d.ts
interface JQuery { fontIconPicker(options
?: any) : any; }

之后,再次启动项目,发现成功启动,大功告成。

 

总结: 如果引入一个js库,但typescript编辑器识别不了,首先应该想到查看该库是否有typings file; 如果有,那么万事大吉,直接安装即可;如果没有,那我们就需要将其declare在 xxx.d.ts文件里面。通常是在src下面的typings.d.ts;编辑器在编译时会自动寻找typings.d.ts文件

 

转载于:https://www.cnblogs.com/juliazhang/p/10103985.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值