自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

【編譯篇】AST實現(xiàn)函數(shù)錯誤的自動上報

開發(fā) 前端
之前有身邊有人問我在錯誤監(jiān)控中,如何能實現(xiàn)自動為函數(shù)自動添加錯誤捕獲。今天我們來聊一聊技術(shù)如何實現(xiàn)。

 前言

之前有身邊有人問我在錯誤監(jiān)控中,如何能實現(xiàn)自動為函數(shù)自動添加錯誤捕獲。今天我們來聊一聊技術(shù)如何實現(xiàn)。先講原理:在代碼編譯時,利用 babel 的 loader,劫持所有函數(shù)表達。然后利用 AST(抽象語法樹) 修改函數(shù)節(jié)點,在函數(shù)外層包裹 try/catch。然后在 catch 中使用 sdk 將錯誤信息在運行時捕獲上報。如果你對編譯打包感興趣,那么本文就是為你準備的。

本文涉及以下知識點:

  •  [x] AST
  •  [x] npm 包開發(fā)
  •  [x] Babel
  •  [x] Babel plugin
  •  [x] Webpack loader

實現(xiàn)效果

Before 開發(fā)環(huán)境: 

  1. var fn = function(){  
  2.   console.log('hello');  

After 線上環(huán)境: 

  1. var fn = function(){  
  2. +  try {  
  3.     console.log('hello');  
  4. +  } catch (error) {  
  5. +    // sdk 錯誤上報  
  6. +    ErrorCapture(error);  
  7. +  }  

Babel 是什么?

Babel 是JS編譯器,主要用于將 ECMAScript 2015+ 版本的代碼轉(zhuǎn)換為向后兼容的 JavaScript 語法,以便能夠運行在當前和舊版本的瀏覽器或其他環(huán)境中。

簡單說就是從一種源碼到另一種源碼的編輯器!下面列出的是 Babel 能為你做的事情:

  •  語法轉(zhuǎn)換
  •  通過 Polyfill 方式在目標環(huán)境中添加缺失的特性 (通過 @babel/polyfill 模塊)
  •  源碼轉(zhuǎn)換 (codemods)
  •  其它

Babel 的運行主要分三個階段,請牢記:解析->轉(zhuǎn)換->生成,后面會用到。

本文我們將會寫一個 Babel plugin 的 npm 包,用于編譯時將代碼進行改造。

babel-plugin 環(huán)境搭建

這里我們使用 yeoman 和 generator-babel-plugin 來構(gòu)建插件的腳手架代碼。安裝: 

  1. $ npm i -g yo  
  2. $ npm i -g generator-babel-plugin 

然后新建文件夾: 

  1. $ mkdir babel-plugin-function-try-actch  
  2. $ cd babel-plugin-function-try-actch 

生成npm包的開發(fā)工程: 

  1. $ yo babel-plugin 

此時項目結(jié)構(gòu)為: 

  1. babel-plugin-function-try-catch  
  2. ├─.babelrc  
  3. ├─.gitignore  
  4. ├─.npmignore  
  5. ├─.travis.yml  
  6. ├─README.md  
  7. ├─package-lock.json  
  8. ├─package.json  
  9. ├─test  
  10. |  ├─index.js  
  11. |  ├─fixtures  
  12. |  |    ├─example  
  13. |  |    |    ├─.babelrc  
  14. |  |    |    ├─actual.js  
  15. |  |    |    └expected.js 
  16. ├─src  
  17. |  └index.js  
  18. ├─lib  
  19. |  └index.js 

這就是我們的 Babel plugin,取名為 babel-loader-function-try-catch(為方便文章閱讀,以下我們統(tǒng)一簡稱為plugin?。?。

至此,npm 包環(huán)境搭建完畢,代碼地址。

調(diào)試 plugin 的 ast

開發(fā)工具

本文前面說過 Babel 的運行主要分三個階段:解析->轉(zhuǎn)換->生成,每個階段 babel 官方提供了核心的 lib:

  •  babel-core。Babel 的核心庫,提供了將代碼編譯轉(zhuǎn)化的能力。
  •  babel-types。提供 AST 樹節(jié)點的類型。
  •  babel-template??梢詫⑵胀ㄗ址D(zhuǎn)化成 AST,提供更便捷的使用

在 plugin 根目錄安裝需要用到的工具包: 

  1. npm i @babel/core @babel/parser babel-traverse @babel/template babel-types -S 

打開 plugin 的 src/index.js 編輯: 

  1. const parser = require("@babel/parser");  
  2. // 先來定義一個簡單的函數(shù)  
  3. let source = `var fn = function (n) {  
  4.   console.log(111)  
  5. }`;  
  6. // 解析為 ast  
  7. let ast = parser.parse(source, {  
  8.   sourceType: "module",  
  9.   plugins: ["dynamicImport"]  
  10. });  
  11. // 打印一下看看,是否正常  
  12. console.log(ast); 

終端執(zhí)行 node src/index.js 后將會打印如下結(jié)果:

這就是 fn 函數(shù)對應的 ast,第一步解析完成!

獲取當前節(jié)點的 AST

然后我們使用 babel-traverse 去遍歷對應的 AST 節(jié)點,我們想要尋找所有的 function 表達可以寫在 FunctionExpression 中:

打開 plugin 的 src/index.js 編輯: 

  1. const parser = require("@babel/parser");  
  2. const traverse = require("babel-traverse").default;  
  3. // mock 待改造的源碼  
  4. let source = `var fn = function() {  
  5.   console.log(111)  
  6. }`; 
  7. // 1、解析  
  8. let ast = parser.parse(source, {  
  9.   sourceType: "module",  
  10.   plugins: ["dynamicImport"]  
  11. });  
  12. // 2、遍歷  
  13. + traverse(ast, {  
  14. +   FunctionExpression(path, state) { // Function 節(jié)點  
  15. +     // do some stuff  
  16. +   },  
  17. + }); 

所有函數(shù)表達都會走到 FunctionExpression 中,然后我們可以在里面對其進行修改。

其中參數(shù) path 用于訪問到當前的節(jié)點信息 path.node,也可以像 DOM 樹訪問到父節(jié)點的方法 path.parent。

修改當前節(jié)點的 AST

好了,接下來要做的是在 FunctionExpression 中去劫持函數(shù)的內(nèi)部代碼,然后將其放入 try 函數(shù)內(nèi),并且在 catch 內(nèi)加入錯誤上報 sdk 的代碼段。

獲取函數(shù)體內(nèi)部代碼

上面定義的函數(shù)是 

  1. var fn = function() {  
  2.   console.log(111)  
  3.  

那么函數(shù)內(nèi)部的代碼塊就是 console.log(111),可以使用 path 拿到這段代碼的 AST 信息,如下: 

  1. const parser = require("@babel/parser");  
  2. const traverse = require("babel-traverse").default;  
  3. // mock 待改造的源碼  
  4. let source = `var fn = function(n) {  
  5.   console.log(111)  
  6. }`;  
  7. // 1、解析  
  8. let ast = parser.parse(source, {  
  9.   sourceType: "module",  
  10.   plugins: ["dynamicImport"]  
  11. });  
  12. // 2、遍歷  
  13. traverse(ast, {  
  14.   FunctionExpression(path, state) { // 函數(shù)表達式會進入當前方法  
  15. +    // 獲取函數(shù)當前節(jié)點信息  
  16. +    var node = path.node,  
  17. +        params = node.params,  
  18. +        blockStatement = node.body,  
  19. +        isGenerator = node.generator,  
  20. +        isAsync = node.async;  
  21. +    // 可以嘗試打印看看結(jié)果  
  22. +    console.log(node, params, blockStatement);  
  23.   },  
  24. }); 

終端執(zhí)行 node src/index.js,可以打印看到當前函數(shù)的 AST 節(jié)點信息。

創(chuàng)建 try/catch 節(jié)點(兩步驟)

創(chuàng)建一個新的節(jié)點可能會稍微陌(fu)生(za)一點,不過我已經(jīng)為大家總結(jié)了我個人的經(jīng)驗(僅供參考)。首先需要知道當前新增代碼段它的聲明是什么,然后使用 @babel-types 去創(chuàng)建即可。

第一步:

那么我們?nèi)绾沃浪谋磉_聲明type是什么呢?這里我們可以 使用 astexplorer 查找它在 AST 中 type 的表達。

如上截圖得知,try/catch 在 AST 中的 type 就是 TryStatement!

第二步:

然后去 @babel-types 官方文檔查找對應方法,根據(jù) API 文檔來創(chuàng)建即可。

如文檔所示,創(chuàng)建一個 try/catch 的方式使用 t.tryStatement(block, handler, finalizer)。

創(chuàng)建新的ast節(jié)點一句話總結(jié):使用 astexplorer 查找你要生成的代碼的 type,再根據(jù) type 在 @babel-types 文檔查找對應的使用方法使用即可!

那么創(chuàng)建 try/catch 只需要使用 t.tryStatement(try代碼塊, catch代碼塊) 即可。

  •  try代碼塊 表示 try 中的函數(shù)代碼塊,即原先函數(shù) body 內(nèi)的代碼 console.log(111),可以直接用 path.node.body 獲取;
  •  catch代碼塊 表示 catch 代碼塊,即我們想要去改造進行錯誤收集上報的 sdk 的代碼 ErrorCapture(error),可以使用 @babel/template 去生成。

代碼如下所示: 

  1. const parser = require("@babel/parser");  
  2. const traverse = require("babel-traverse").default;  
  3. const t = require("babel-types");  
  4. const template = require("@babel/template");  
  5. // 0、定義一個待處理的函數(shù)(mock)  
  6. let source = `var fn = function() {  
  7.   console.log(111)  
  8. }`;  
  9. // 1、解析 
  10.  let ast = parser.parse(source, {  
  11.   sourceType: "module",  
  12.   plugins: ["dynamicImport"]  
  13. });  
  14. // 2、遍歷  
  15. traverse(ast, {  
  16.   FunctionExpression(path, state) { // Function 節(jié)點  
  17.     var node = path.node,  
  18.         params = node.params,  
  19.         blockStatement = node.body, // 函數(shù)function內(nèi)部代碼,將函數(shù)內(nèi)部代碼塊放入 try 節(jié)點  
  20.         isGenerator = node.generator,  
  21.         isAsync = node.async; 
  22. +    // 創(chuàng)建 catch 節(jié)點中的代碼  
  23. +    var catchStatement = template.statement(`ErrorCapture(error)`)();  
  24. +    var catchClause = t.catchClause(t.identifier('error'),  
  25. +          t.blockStatement(  
  26. +            [catchStatement] //  catchBody  
  27. +          )  
  28. +        );  
  29. +    // 創(chuàng)建 try/catch 的 ast  
  30. +    var ttryStatement = t.tryStatement(blockStatement, catchClause);  
  31.   }  
  32. }); 

創(chuàng)建新函數(shù)節(jié)點,并將上面定義好的 try/catch 塞入函數(shù)體: 

  1. const parser = require("@babel/parser");  
  2. const traverse = require("babel-traverse").default;  
  3. const t = require("babel-types");  
  4. const template = require("@babel/template");  
  5. // 0、定義一個待處理的函數(shù)(mock)  
  6. let source = `var fn = function() {  
  7.   console.log(111)  
  8. }`;  
  9. // 1、解析  
  10. let ast = parser.parse(source, {  
  11.   sourceType: "module",  
  12.   plugins: ["dynamicImport"]  
  13. });  
  14. // 2、遍歷  
  15. traverse(ast, {  
  16.   FunctionExpression(path, state) { // Function 節(jié)點  
  17.       var node = path.node,  
  18.           params = node.params,  
  19.           blockStatement = node.body, // 函數(shù)function內(nèi)部代碼,將函數(shù)內(nèi)部代碼塊放入 try 節(jié)點  
  20.           isGenerator = node.generator,  
  21.           isAsync = node.async;  
  22.       // 創(chuàng)建 catch 節(jié)點中的代碼  
  23.       var catchStatement = template.statement(`ErrorCapture(error)`)();  
  24.       var catchClause = t.catchClause(t.identifier('error'),  
  25.             t.blockStatement(  
  26.               [catchStatement] //  catchBody  
  27.             )  
  28.           );  
  29.       // 創(chuàng)建 try/catch 的 ast 
  30.        var ttryStatement = t.tryStatement(blockStatement, catchClause);  
  31. +    // 創(chuàng)建新節(jié)點  
  32. +    var func = t.functionExpression(node.id, params, t.BlockStatement([tryStatement]), isGenerator, isAsync);  
  33. +    // 打印看看是否成功  
  34. +    console.log('當前節(jié)點是:', func);  
  35. +    console.log('當前節(jié)點下的自節(jié)點是:', func.body);  
  36.   }  
  37. }); 

此時將上述代碼在終端執(zhí)行 node src/index.js:

可以看到此時我們在一個函數(shù)表達式 body 中創(chuàng)建了一個 try 函數(shù)(TryStatement)。

最后我們需要將原函數(shù)節(jié)點進行替換: 

  1. const parser = require("@babel/parser");  
  2. const traverse = require("babel-traverse").default;  
  3. const t = require("babel-types");  
  4. const template = require("@babel/template");  
  5. // 0、定義一個待處理的函數(shù)(mock)  
  6. let source = `var fn = function() {...  
  7. // 1、解析  
  8. let ast = parser.parse(source, {...  
  9. // 2、遍歷  
  10. traverse(ast, {  
  11.   FunctionExpression(path, state) { // Function 節(jié)點  
  12.       var node = path.node,  
  13.           params = node.params,  
  14.           blockStatement = node.body, // 函數(shù)function內(nèi)部代碼,將函數(shù)內(nèi)部代碼塊放入 try 節(jié)點  
  15.           isGenerator = node.generator,  
  16.           isAsync = node.async;  
  17.       // 創(chuàng)建 catch 節(jié)點中的代碼  
  18.       var catchStatement = template.statement(`ErrorCapture(error)`)();  
  19.       var catchClause = t.catchClause(t.identifier('error'),...  
  20.       // 創(chuàng)建 try/catch 的 ast  
  21.       var ttryStatement = t.tryStatement(blockStatement, catchClause);  
  22.       // 創(chuàng)建新節(jié)點  
  23.       var func = t.functionExpression(node.id, params, t.BlockStatement([tryStatement]), isGenerator, isAsync);    
  24.  +    // 替換原節(jié)點 
  25. +    path.replaceWith(func);  
  26.   }  
  27. });  
  28. + // 將新生成的 AST,轉(zhuǎn)為 Source 源碼:  
  29. + return core.transformFromAstSync(ast, null, {  
  30. +  configFile: false // 屏蔽 babel.config.js,否則會注入 polyfill 使得調(diào)試變得困難  
  31. + }).code; 

“A loader is a node module exporting a function”,也就是說一個 loader 就是一個暴露出去的 node 模塊,既然是一個node module,也就基本可以寫成下面的樣子: 

  1. module.exports = function() {  
  2.     //  ... 
  3.  }; 

再編輯 src/index.js 為如下截圖:

邊界條件處理

我們并不需要為所有的函數(shù)都增加 try/catch,所有我們還得處理一些邊界條件。

  •  1、如果有 try catch 包裹了
  •  2、防止 circle loops
  •  3、需要 try catch 的只能是語句,像 () => 0 這種的 body
  •  4、如果函數(shù)內(nèi)容小于多少行數(shù)

滿足以上條件就 return 掉!

代碼如下: 

  1. if (blockStatement.body && t.isTryStatement(blockStatement.body[0])  
  2.   || !t.isBlockStatement(blockStatement) && !t.isExpressionStatement(blockStatement)  
  3.   || blockStatement.body && blockStatement.body.length <= LIMIT_LINE) {  
  4.   return;  
  5.  

最后我們發(fā)布到 npm 平臺 使用。

由于篇幅過長不易閱讀,本文特別的省略了本地調(diào)試過程,所以需要調(diào)試請移步 [【利用AST自動為函數(shù)增加錯誤上報-續(xù)集】有關(guān) npm 包的本地開發(fā)和調(diào)試]()。

如何使用 

  1. npm install babel-plugin-function-try-catch 

webpack 配置 

  1. rules: [{  
  2.   test: /\.js$/,  
  3.   exclude: /node_modules/,  
  4.   use: [  
  5. +   "babel-plugin-function-try-catch",  
  6.     "babel-loader",  
  7.   ]  
  8. }] 

效果見如下圖所示:

  

 

責任編輯:龐桂玉 來源: segmentfault
相關(guān)推薦

2013-01-21 09:41:00

路由器設(shè)備故障設(shè)置參數(shù)

2019-02-20 09:24:12

AST IDE語法

2022-12-07 10:34:45

AST前端編譯

2009-08-20 11:38:15

C#二維數(shù)組

2020-11-18 08:13:45

瀏覽器Reporting A

2022-08-31 08:09:35

Vue2AST模版

2021-10-08 23:07:02

工具AST編譯

2010-02-02 17:33:35

Python函數(shù)編譯

2010-10-20 13:43:37

C++編譯器

2017-03-07 18:34:40

Windows 10Windows移動硬盤

2022-01-18 18:46:55

Eslint抽象語法樹Babel

2024-08-27 08:38:34

2019-09-19 09:41:58

C語言Go語言Java

2024-01-18 11:10:17

2024-08-23 13:40:57

2021-07-06 09:29:38

Cobar源碼AST

2011-03-08 15:47:32

函數(shù)式編程

2021-06-16 17:46:55

函數(shù)指針結(jié)構(gòu)

2010-09-17 08:40:49

JAVA編譯錯誤

2011-07-04 10:56:10

Qt 移植 編譯
點贊
收藏

51CTO技術(shù)棧公眾號