More Related Content More from Will Huang (20) Angular 與 jQuery 共舞:整合第三方套件的技巧、陷阱與解決方案1. Angular 與 jQuery 共舞
整合第三方套件的技巧、陷阱與解決方案
多奇數位創意有限公司
技術總監 黃保翕 ( Will 保哥 )
部落格:http://blog.miniasp.com/
3. 兩種整合方法
• 以全域函式庫載入 (Imported as a global library)
– 就是原本 JS 套件的載入方式 ( 放入 src/index.html 首頁 )
<script src="jquery.js"></script>
• 以 JS 模組方式載入 (Imported as a module)
– 將 JS 套件直接內嵌到 Angular 專案內
PS> npm install jquery
import * as $ from "jquery";
5. 載入全域函式庫的兩種方法
• 從首頁載入 ( src/index.html )
<script src="https://code.jquery.com/jquery-
3.2.1.min.js"></script>
• 從 Angular CLI 定義檔載入 ( .angular-cli.json )
"styles": [ "styles.css" ],
"scripts": [
"global-script.js",
{ "input": "lazy-script.js", "lazy": true },
{ "input": "pre-rename-script.js",
"output": "renamed-script" }
],
5
6. 在 TypeScript 中使用全域函式庫
• 沒有 TypeScript 模組定義檔
– 建立 src/typings.d.ts 檔案 ( 此檔案 Angular CLI 已內建 )
declare var $: any;
• 已有 TypeScript 模組定義檔
– 搜尋 @types 工具:http://microsoft.github.io/TypeSearch/
PS> npm install @types/jquery
PS> npm install @types/d3
6
7. 安裝與設定 TypeScript 模組定義檔
• 安裝 TypeScript 模組定義檔
PS> npm install @types/jquery
• 設定 tsconfig.json 設定檔 (預設會自動載入模組定義檔)
"typeRoots": [
"node_modules/@types"
],
7
10. 不同的 tsconfig.json 設定檔 (明確載入)
• src/tsconfig.app.json
"types": []
• src/tsconfig.spec.json
e2e/tsconfig.e2e.json
"types": [
"jasmine",
"node"
]
10
11. 載入 jQuery 其他外掛 (Plugins)
• 常見錯誤訊息
[TS][Error] Property 'myPlugin' does not exist on type 'JQuery'.
• 沒有 TypeScript 模組定義檔的解決方案 ( src/typings.d.ts )
interface JQuery {
myPlugin(options?: any): any;
}
• 已有 TypeScript 模組定義檔的解決方案
PS> npm install @types/jqueryui
11
13. 以 JS 模組方式載入
• 沒有 TypeScript 模組定義檔
– 建立 src/typings.d.ts 檔案 ( 此檔案 Angular CLI 已內建 )
declare module 'typeless-package';
declare module 'jquery';
• 已有 TypeScript 模組定義檔
– 搜尋 @types 工具:http://microsoft.github.io/TypeSearch/
PS> npm install @types/jquery
13
15. 關於 Zones 機制
• 從 Angular 2 開始加入了非常神奇的 Zones 機制
• 主要用途
– 管理非同步事件的執行與錯誤追蹤
– 可以精準掌握非同步事件的運作時機
– 可以更清楚地記錄錯誤發生時的呼叫堆疊
• 服務元件
– 預設 Angular 就是以 NgZone 進行非同步事件管理
– 應用程式生命週期中所有非同步事件都由 NgZone 管理
– 你可以在元件中注入 NgZone 服務元件管理事件執行
15
16. 示範 NgZone 的威力
• 範本
<div> {{ debug() }} </div>
• 元件
ngOnInit() {
document.addEventListener('click',
x => console.log(x));
}
debug() {
console.log('DEBUG:'+(new Date().getTime()));
}
16
19. 相關連結
• Global Library Installation
• Global scripts
• 3rd Party Library Installation
• Using global libraries inside your app
19
20. 聯絡資訊
• The Will Will Web
記載著 Will 在網路世界的學習心得與技術分享
– http://blog.miniasp.com/
• Will 保哥的技術交流中心 (臉書粉絲專頁)
– http://www.facebook.com/will.fans
• Will 保哥的噗浪
– http://www.plurk.com/willh/invite
• Will 保哥的推特
– https://twitter.com/Will_Huang
Editor's Notes https://code.jquery.com/jquery-3.2.1.min.js 如何在 runtime 時期覆寫底層的 API?
Angular 使用 Zone.js 讓 sync (同步) 和 async (非同步) 操作都在同一個 JavaScript 運行空間下依序執行。
Zone.js 支援瀏覽器的 async APIs。
all browser events (click, mouseover, keyup, etc.)
setTimeout() and setInterval()
Ajax requests
這種機制有個限制,如果有 Zone.js 不支援的 async browser API,那麼變更偵測不會被觸發。
例如 IndexedDB 的 callback。