分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

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

发布时间:2023-09-06 02:25责任编辑:彭小芳关键词:Angularscript

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 plugininitFontIconPicker( 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文件

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

原文地址:https://www.cnblogs.com/juliazhang/p/10103985.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved