AST 實(shí)現(xiàn)函數(shù)錯(cuò)誤自動(dòng)上報(bào)
(給前端大學(xué)加星標(biāo),提升前端技能.)
作者:哈啰出行-杭州團(tuán)隊(duì)Allan
https://segmentfault.com/a/1190000037630766
前言
之前有身邊有人問(wèn)我在錯(cuò)誤監(jiān)控中,如何能實(shí)現(xiàn)自動(dòng)為函數(shù)自動(dòng)添加錯(cuò)誤捕獲。今天我們來(lái)聊一聊技術(shù)如何實(shí)現(xiàn)。先講原理:在代碼編譯時(shí),利用 babel 的 loader,劫持所有函數(shù)表達(dá)。然后利用?AST(抽象語(yǔ)法樹(shù))?修改函數(shù)節(jié)點(diǎn),在函數(shù)外層包裹 try/catch。然后在 catch 中使用 sdk 將錯(cuò)誤信息在運(yùn)行時(shí)捕獲上報(bào)。如果你對(duì)編譯打包感興趣,那么本文就是為你準(zhǔn)備的。
本文涉及以下知識(shí)點(diǎn):
[x] AST [x] npm 包開(kāi)發(fā) [x] Babel [x] Babel plugin [x] Webpack loader
實(shí)現(xiàn)效果
Before?開(kāi)發(fā)環(huán)境:
var?fn?=?function(){
??console.log('hello');
}
After?線上環(huán)境:
var?fn?=?function(){
+??try?{
????console.log('hello');
+??}?catch?(error)?{
+????//?sdk?錯(cuò)誤上報(bào)
+????ErrorCapture(error);
+??}
}
Babel 是什么?
Babel 是JS編譯器,主要用于將 ECMAScript 2015+ 版本的代碼轉(zhuǎn)換為向后兼容的 JavaScript 語(yǔ)法,以便能夠運(yùn)行在當(dāng)前和舊版本的瀏覽器或其他環(huán)境中。簡(jiǎn)單說(shuō)就是從一種源碼到另一種源碼的編輯器!下面列出的是 Babel 能為你做的事情:
語(yǔ)法轉(zhuǎn)換 通過(guò) Polyfill 方式在目標(biāo)環(huán)境中添加缺失的特性 (通過(guò)? @babel/polyfill?模塊)源碼轉(zhuǎn)換 (codemods) 其它
Babel 的運(yùn)行主要分三個(gè)階段,請(qǐng)牢記:解析->轉(zhuǎn)換->生成,后面會(huì)用到。
本文我們將會(huì)寫(xiě)一個(gè) Babel plugin 的 npm 包,用于編譯時(shí)將代碼進(jìn)行改造。
babel-plugin 環(huán)境搭建
這里我們使用?yeoman?和?generator-babel-plugin?來(lái)構(gòu)建插件的腳手架代碼。安裝:
$?npm?i?-g?yo
$?npm?i?-g?generator-babel-plugin
然后新建文件夾:
$?mkdir?babel-plugin-function-try-actch
$?cd?babel-plugin-function-try-actch
生成npm包的開(kāi)發(fā)工程:
$?yo?babel-plugin
此時(shí)項(xiàng)目結(jié)構(gòu)為:
babel-plugin-function-try-catch
├─.babelrc
├─.gitignore
├─.npmignore
├─.travis.yml
├─README.md
├─package-lock.json
├─package.json
├─test
| ├─index.js
| ├─fixtures
| | ├─example
| | | ├─.babelrc
| | | ├─actual.js
| | | └expected.js
├─src
| └index.js
├─lib
| └index.js
這就是我們的 Babel plugin,取名為?babel-loader-function-try-catch(為方便文章閱讀,以下我們統(tǒng)一簡(jiǎn)稱(chēng)為plugin!)。
至此,npm 包環(huán)境搭建完畢,代碼地址。
調(diào)試 plugin 的 ast
開(kāi)發(fā)工具
本文前面說(shuō)過(guò) Babel 的運(yùn)行主要分三個(gè)階段:解析->轉(zhuǎn)換->生成,每個(gè)階段 babel 官方提供了核心的 lib:
babel-core。Babel 的核心庫(kù),提供了將代碼編譯轉(zhuǎn)化的能力。 babel-types。提供 AST 樹(shù)節(jié)點(diǎn)的類(lèi)型。 babel-template??梢詫⑵胀ㄗ址D(zhuǎn)化成 AST,提供更便捷的使用
在?plugin?根目錄安裝需要用到的工具包:
npm?i?@babel/core?@babel/parser?babel-traverse?@babel/template?babel-types?-S
打開(kāi)?plugin?的 src/index.js 編輯:
const?parser?=?require("@babel/parser");
//?先來(lái)定義一個(gè)簡(jiǎn)單的函數(shù)
let?source?=?`var?fn?=?function?(n)?{
??console.log(111)
}`;
//?解析為?ast
let?ast?=?parser.parse(source,?{
??sourceType:?"module",
??plugins:?["dynamicImport"]
});
//?打印一下看看,是否正常
console.log(ast);
終端執(zhí)行?node src/index.js?后將會(huì)打印如下結(jié)果:
這就是 fn 函數(shù)對(duì)應(yīng)的 ast,第一步解析完成!
獲取當(dāng)前節(jié)點(diǎn)的 AST
然后我們使用?babel-traverse?去遍歷對(duì)應(yīng)的 AST 節(jié)點(diǎn),我們想要尋找所有的 function 表達(dá)可以寫(xiě)在?FunctionExpression?中:
打開(kāi)?plugin?的 src/index.js 編輯:
const?parser?=?require("@babel/parser");
const?traverse?=?require("babel-traverse").default;
//?mock?待改造的源碼
let?source?=?`var?fn?=?function()?{
??console.log(111)
}`;
//?1、解析
let?ast?=?parser.parse(source,?{
??sourceType:?"module",
??plugins:?["dynamicImport"]
});
//?2、遍歷
+?traverse(ast,?{
+???FunctionExpression(path,?state)?{?//?Function?節(jié)點(diǎn)
+?????//?do?some?stuff
+???},
+?});
所有函數(shù)表達(dá)都會(huì)走到?FunctionExpression?中,然后我們可以在里面對(duì)其進(jìn)行修改。其中參數(shù)?path?用于訪問(wèn)到當(dāng)前的節(jié)點(diǎn)信息?path.node,也可以像 DOM 樹(shù)訪問(wèn)到父節(jié)點(diǎn)的方法?path.parent。
修改當(dāng)前節(jié)點(diǎn)的 AST
好了,接下來(lái)要做的是在?FunctionExpression?中去劫持函數(shù)的內(nèi)部代碼,然后將其放入 try 函數(shù)內(nèi),并且在 catch 內(nèi)加入錯(cuò)誤上報(bào) sdk 的代碼段。
獲取函數(shù)體內(nèi)部代碼
上面定義的函數(shù)是
var?fn?=?function()?{
??console.log(111)
}
那么函數(shù)內(nèi)部的代碼塊就是?console.log(111),可以使用?path?拿到這段代碼的 AST 信息,如下:
const?parser?=?require("@babel/parser");
const?traverse?=?require("babel-traverse").default;
//?mock?待改造的源碼
let?source?=?`var?fn?=?function(n)?{
??console.log(111)
}`;
//?1、解析
let?ast?=?parser.parse(source,?{
??sourceType:?"module",
??plugins:?["dynamicImport"]
});
//?2、遍歷
traverse(ast,?{
??FunctionExpression(path,?state)?{?//?函數(shù)表達(dá)式會(huì)進(jìn)入當(dāng)前方法
+????//?獲取函數(shù)當(dāng)前節(jié)點(diǎn)信息
+????var?node?=?path.node,
+????????params?=?node.params,
+????????blockStatement?=?node.body,
+????????isGenerator?=?node.generator,
+????????isAsync?=?node.async;
+????//?可以嘗試打印看看結(jié)果
+????console.log(node,?params,?blockStatement);
??},
});
終端執(zhí)行?node src/index.js,可以打印看到當(dāng)前函數(shù)的 AST 節(jié)點(diǎn)信息。
創(chuàng)建 try/catch 節(jié)點(diǎn)(兩步驟)
創(chuàng)建一個(gè)新的節(jié)點(diǎn)可能會(huì)稍微陌(fu)生(za)一點(diǎn),不過(guò)我已經(jīng)為大家總結(jié)了我個(gè)人的經(jīng)驗(yàn)(僅供參考)。首先需要知道當(dāng)前新增代碼段它的聲明是什么,然后使用?@babel-types?去創(chuàng)建即可。
第一步:
那么我們?nèi)绾沃浪谋磉_(dá)聲明type是什么呢?這里我們可以?使用?astexplorer?查找它在 AST 中 type 的表達(dá)。
如上截圖得知,try/catch 在 AST 中的 type 就是?TryStatement!
第二步:
然后去?@babel-types 官方文檔查找對(duì)應(yīng)方法,根據(jù) API 文檔來(lái)創(chuàng)建即可。
如文檔所示,創(chuàng)建一個(gè) try/catch 的方式使用?t.tryStatement(block, handler, finalizer)。
創(chuàng)建新的ast節(jié)點(diǎn)一句話總結(jié):使用 astexplorer 查找你要生成的代碼的 type,再根據(jù) type 在?@babel-types?文檔查找對(duì)應(yīng)的使用方法使用即可!
那么創(chuàng)建 try/catch 只需要使用?t.tryStatement(try代碼塊, catch代碼塊)?即可。
try代碼塊?表示 try 中的函數(shù)代碼塊,即原先函數(shù) body 內(nèi)的代碼?console.log(111),可以直接用?path.node.body?獲??;catch代碼塊?表示 catch 代碼塊,即我們想要去改造進(jìn)行錯(cuò)誤收集上報(bào)的 sdk 的代碼?ErrorCapture(error),可以使用 @babel/template 去生成。
代碼如下所示:
const?parser?=?require("@babel/parser");
const?traverse?=?require("babel-traverse").default;
const?t?=?require("babel-types");
const?template?=?require("@babel/template");
//?0、定義一個(gè)待處理的函數(shù)(mock)
let?source?=?`var?fn?=?function()?{
??console.log(111)
}`;
//?1、解析
let?ast?=?parser.parse(source,?{
??sourceType:?"module",
??plugins:?["dynamicImport"]
});
//?2、遍歷
traverse(ast,?{
??FunctionExpression(path,?state)?{?//?Function?節(jié)點(diǎn)
????var?node?=?path.node,
????????params?=?node.params,
????????blockStatement?=?node.body,?//?函數(shù)function內(nèi)部代碼,將函數(shù)內(nèi)部代碼塊放入?try?節(jié)點(diǎn)
????????isGenerator?=?node.generator,
????????isAsync?=?node.async;
+????//?創(chuàng)建?catch?節(jié)點(diǎn)中的代碼
+????var?catchStatement?=?template.statement(`ErrorCapture(error)`)();
+????var?catchClause?=?t.catchClause(t.identifier('error'),
+??????????t.blockStatement(
+????????????[catchStatement]?//??catchBody
+??????????)
+????????);
+????//?創(chuàng)建?try/catch?的?ast
+????var?tryStatement?=?t.tryStatement(blockStatement,?catchClause);
??}
});
創(chuàng)建新函數(shù)節(jié)點(diǎn),并將上面定義好的?try/catch?塞入函數(shù)體:
const?parser?=?require("@babel/parser");
const?traverse?=?require("babel-traverse").default;
const?t?=?require("babel-types");
const?template?=?require("@babel/template");
//?0、定義一個(gè)待處理的函數(shù)(mock)
let?source?=?`var?fn?=?function()?{
??console.log(111)
}`;
//?1、解析
let?ast?=?parser.parse(source,?{
??sourceType:?"module",
??plugins:?["dynamicImport"]
});
//?2、遍歷
traverse(ast,?{
??FunctionExpression(path,?state)?{?//?Function?節(jié)點(diǎn)
??????var?node?=?path.node,
??????????params?=?node.params,
??????????blockStatement?=?node.body,?//?函數(shù)function內(nèi)部代碼,將函數(shù)內(nèi)部代碼塊放入?try?節(jié)點(diǎn)
??????????isGenerator?=?node.generator,
??????????isAsync?=?node.async;
??????//?創(chuàng)建?catch?節(jié)點(diǎn)中的代碼
??????var?catchStatement?=?template.statement(`ErrorCapture(error)`)();
??????var?catchClause?=?t.catchClause(t.identifier('error'),
????????????t.blockStatement(
??????????????[catchStatement]?//??catchBody
????????????)
??????????);
??????//?創(chuàng)建?try/catch?的?ast
??????var?tryStatement?=?t.tryStatement(blockStatement,?catchClause);
+????//?創(chuàng)建新節(jié)點(diǎn)
+????var?func?=?t.functionExpression(node.id,?params,?t.BlockStatement([tryStatement]),?isGenerator,?isAsync);
+????//?打印看看是否成功
+????console.log('當(dāng)前節(jié)點(diǎn)是:',?func);
+????console.log('當(dāng)前節(jié)點(diǎn)下的自節(jié)點(diǎn)是:',?func.body);
??}
});
此時(shí)將上述代碼在終端執(zhí)行?node src/index.js:
可以看到此時(shí)我們?cè)谝粋€(gè)函數(shù)表達(dá)式 body 中創(chuàng)建了一個(gè) try 函數(shù)(TryStatement)。最后我們需要將原函數(shù)節(jié)點(diǎn)進(jìn)行替換:
const?parser?=?require("@babel/parser");
const?traverse?=?require("babel-traverse").default;
const?t?=?require("babel-types");
const?template?=?require("@babel/template");
//?0、定義一個(gè)待處理的函數(shù)(mock)
let?source?=?`var?fn?=?function()?{...
//?1、解析
let?ast?=?parser.parse(source,?{...
//?2、遍歷
traverse(ast,?{
??FunctionExpression(path,?state)?{?//?Function?節(jié)點(diǎn)
??????var?node?=?path.node,
??????????params?=?node.params,
??????????blockStatement?=?node.body,?//?函數(shù)function內(nèi)部代碼,將函數(shù)內(nèi)部代碼塊放入?try?節(jié)點(diǎn)
??????????isGenerator?=?node.generator,
??????????isAsync?=?node.async;
??????//?創(chuàng)建?catch?節(jié)點(diǎn)中的代碼
??????var?catchStatement?=?template.statement(`ErrorCapture(error)`)();
??????var?catchClause?=?t.catchClause(t.identifier('error'),...
??????//?創(chuàng)建?try/catch?的?ast
??????var?tryStatement?=?t.tryStatement(blockStatement,?catchClause);
??????//?創(chuàng)建新節(jié)點(diǎn)
??????var?func?=?t.functionExpression(node.id,?params,?t.BlockStatement([tryStatement]),?isGenerator,?isAsync);
??????
+????//?替換原節(jié)點(diǎn)
+????path.replaceWith(func);
??}
});
+?//?將新生成的 AST,轉(zhuǎn)為 Source 源碼:
+?return?core.transformFromAstSync(ast,?null,?{
+??configFile:?false?//?屏蔽?babel.config.js,否則會(huì)注入?polyfill?使得調(diào)試變得困難
+?}).code;
“A loader is a node module exporting a function”,也就是說(shuō)一個(gè) loader 就是一個(gè)暴露出去的 node 模塊,既然是一個(gè)node module,也就基本可以寫(xiě)成下面的樣子:
module.exports?=?function()?{
????//??...
};
再編輯 src/index.js 為如下截圖:
邊界條件處理
我們并不需要為所有的函數(shù)都增加 try/catch,所有我們還得處理一些邊界條件。
1、如果有 try catch 包裹了 2、防止 circle loops 3、需要 try catch 的只能是語(yǔ)句,像 () => 0 這種的 body 4、如果函數(shù)內(nèi)容小于多少行數(shù)
滿(mǎn)足以上條件就 return 掉!
代碼如下:
if?(blockStatement.body?&&?t.isTryStatement(blockStatement.body[0])
??||?!t.isBlockStatement(blockStatement)?&&?!t.isExpressionStatement(blockStatement)
??||?blockStatement.body?&&?blockStatement.body.length?<=?LIMIT_LINE)?{
??return;
}
最后我們發(fā)布到 npm 平臺(tái)?使用。
由于篇幅過(guò)長(zhǎng)不易閱讀,本文特別的省略了本地調(diào)試過(guò)程,所以需要調(diào)試請(qǐng)移步?【利用AST自動(dòng)為函數(shù)增加錯(cuò)誤上報(bào)-續(xù)集】有關(guān) npm 包的本地開(kāi)發(fā)和調(diào)試。
如何使用
npm?install?babel-plugin-function-try-catch
webpack 配置
rules:?[{
??test:?/\.js$/,
??exclude:?/node_modules/,
??use:?[
+???"babel-plugin-function-try-catch",
????"babel-loader",
??]
}]
效果見(jiàn)如下圖所示:

最后
有關(guān) npm 包的本地調(diào)試見(jiàn)下篇:?有關(guān) npm 包的本地開(kāi)發(fā)和調(diào)試:https://juejin.im/post/6888493557716353032/
更多 AST 相關(guān)請(qǐng)關(guān)注后面分享,謝謝。
Reference:
完整代碼地址請(qǐng)點(diǎn)擊:https://github.com/allan2coder/babel-plugin-function-try-catch
Babel 插件手冊(cè)點(diǎn)擊:https://github.com/jamiebuilds/babel-handbook/blob/master/translations/zh-Hans/plugin-handbook.md

