集成步驟:
1、安裝jquery極其擴展插件庫ts定義文件
npm install jquery --save npm install --save-dev @types/jquery npm install datatables.net --save npm install @types/datatables.net --save-dev
2、頁面加載jquery和擴展插件:
"apps": [{ ... "scripts": [ "../node_modules/jquery/dist/jquery.min.js", "../node_modules/datatables.net/js/jquery.dataTables.js", ], ... }]
3、把擴展插件module加入到tsconfig.app.json的types配置。
"types": [ "echarts", "datatables.net", "bootstrap", "admin-lte" ]
4、調用擴展插件的方法:
$("selector").pluginMethod();
5、運行ng serve:
ng serve -o
這個里面有個問題,就是我們不是直接去嘗試調用jquery plugin,jquery接口的ts定義擴展是通過plugin的d.ts文件去擴展的,我們調用jquery本身,在編譯時,編譯器自動去尋找相關的plugin定義並擴展原始jquery的接口。搞清楚這一點,很多基於jQuery選擇器函數的JS庫集成就方便多了。
最后分析幾個錯誤:
1、編譯的時候出現
Property 'DataTable' does not exist on type 'JQuery<HTMLElement>'.
是因為定義DataTable的datatables.net庫沒有放進types設置,導致編譯時找不到這個方法定義。
2、Lint的時候出現錯誤:
Error:(5, 22) TS2306:File '/Users/denghui/ng/ord/node_modules/@types/datatables.net/index.d.ts' is not a module.
是因為JQuery和他的插件都是全局庫,一是沒有必要用import語法導入,二是它的types定義里面也沒有module定義,所以import時出現這個錯誤,解決方法是全局庫極其插件無需導入,直接使用jQuery釋放的$接口即可。
參考資料:https://stackoverflow.com/questions/43934727/how-to-use-jquery-plugin-with-angular-4