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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM