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