當我們的應用程式部署到生產環境時,我們發現它與我們在開發環境時的代碼不同,我們的代碼在構建程序中會以各種方式進行修改和優化,
TypeScript 被轉譯、壓縮,生成的 JavaScript 包盡可能小并且能夠在瀏覽器中正常運行,
所有這些步驟都很有效率,它們提高了我們應用程式在生產環境下的性能,但是當我們需要在生產環境下除錯代碼時它對我們產生了很大的障礙,
但是有一個解決方案:Source Map
配合Chrome 開發工具可以為我們提供一個debug線上專案的功能
Source Map簡介:
從技術上講,source maps只是一個包含以下欄位的 JSON 檔案:
- version: 表示source map版本
- file: source map所屬的轉譯后檔案的名稱
- sourceRoot: basePath — 源相對于這里
- sources: 原始源檔案的路徑(例如 TypeScript 檔案)
- sourcesContent: 可選屬性,可以包含整個源代碼,
- names: 在代碼中找到的方法或變數名稱
- mappings: 這是整個功能起作用的關鍵,從技術上講, mappings 屬性是一個非常大的字串,其中包含 Base64 VLQ(可變長度數量)值,這些值有助于找到源檔案中的原始位置,
專案環境:
使用 @angular/cli 12.0.3 所搭建的標準 Angular 專案
{
"name": "sourcemap",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "~12.0.3",
"@angular/common": "~12.0.3",
"@angular/compiler": "~12.0.3",
"@angular/core": "~12.0.3",
"@angular/forms": "~12.0.3",
"@angular/platform-browser": "~12.0.3",
"@angular/platform-browser-dynamic": "~12.0.3",
"@angular/router": "~12.0.3",
"rxjs": "~6.6.0",
"tslib": "^2.1.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "~12.0.3",
"@angular/cli": "~12.0.3",
"@angular/compiler-cli": "~12.0.3",
"@types/jasmine": "~3.6.0",
"@types/node": "^12.11.1",
"jasmine-core": "~3.7.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"typescript": "~4.2.3"
}
}
debug步驟:
使用Source Map進行除錯還需要一些步驟,一般情況下專案的 source maps檔案是不會在生產環境下被生成的,以防止源代碼泄露,
angular.json 檔案包含一個sourceMap屬性,允許我們指定是否要在生產構建中使用它
"architect": {
"build": {
…
"configurations": {
"production": {
…
"sourceMap": true
}
},
"defaultConfiguration": "production"
}
}
或者添加下列命令列進行覆寫 (Angular 7.2版本以下的專案需要使用命令列方式)
--source-map=true
現在如我們所見,在build執行完后,dist中出現了js.map檔案
注意:確保你要除錯的本地代碼與線上代碼相同

現在我們可以使用 Chrome 開發工具從本地檔案系統上傳js.map,
打開開發工具并右鍵單擊,找到需要除錯的js以及與其相對的 js.map檔案,記錄路徑,現在輸入js.map檔案路徑,
注意:必須通過以下方式添加路徑: file:///pathToFile
我們也可以使用瀏覽器打開js.map,這樣瀏覽器上方的地址欄就自動生成了我們需要的path


如果左側出現了webpack://,則表示source map已經成功匯入,可以除錯對應的原始碼

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/289836.html
標籤:其他
