【編譯篇】AST實現(xiàn)函數(shù)錯誤的自動上報
前言
之前有身邊有人問我在錯誤監(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)境:
- var fn = function(){
- console.log('hello');
- }
After 線上環(huán)境:
- var fn = function(){
- + try {
- console.log('hello');
- + } catch (error) {
- + // sdk 錯誤上報
- + ErrorCapture(error);
- + }
- }
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)建插件的腳手架代碼。安裝:
- $ npm i -g yo
- $ npm i -g generator-babel-plugin
然后新建文件夾:
- $ mkdir babel-plugin-function-try-actch
- $ cd babel-plugin-function-try-actch
生成npm包的開發(fā)工程:
- $ yo babel-plugin
此時項目結(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)一簡稱為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 根目錄安裝需要用到的工具包:
- npm i @babel/core @babel/parser babel-traverse @babel/template babel-types -S
打開 plugin 的 src/index.js 編輯:
- const parser = require("@babel/parser");
- // 先來定義一個簡單的函數(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 后將會打印如下結(jié)果:
這就是 fn 函數(shù)對應的 ast,第一步解析完成!
獲取當前節(jié)點的 AST
然后我們使用 babel-traverse 去遍歷對應的 AST 節(jié)點,我們想要尋找所有的 function 表達可以寫在 FunctionExpression 中:
打開 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é)點
- + // do some stuff
- + },
- + });
所有函數(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ù)是
- 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ù)表達式會進入當前方法
- + // 獲取函數(shù)當前節(jié)點信息
- + 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,可以打印看到當前函數(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 去生成。
代碼如下所示:
- const parser = require("@babel/parser");
- const traverse = require("babel-traverse").default;
- const t = require("babel-types");
- const template = require("@babel/template");
- // 0、定義一個待處理的函數(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é)點
- var node = path.node,
- params = node.params,
- blockStatement = node.body, // 函數(shù)function內(nèi)部代碼,將函數(shù)內(nèi)部代碼塊放入 try 節(jié)點
- isGenerator = node.generator,
- isAsync = node.async;
- + // 創(chuàng)建 catch 節(jié)點中的代碼
- + var catchStatement = template.statement(`ErrorCapture(error)`)();
- + var catchClause = t.catchClause(t.identifier('error'),
- + t.blockStatement(
- + [catchStatement] // catchBody
- + )
- + );
- + // 創(chuàng)建 try/catch 的 ast
- + var ttryStatement = t.tryStatement(blockStatement, catchClause);
- }
- });
創(chuàng)建新函數(shù)節(jié)點,并將上面定義好的 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、定義一個待處理的函數(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é)點
- var node = path.node,
- params = node.params,
- blockStatement = node.body, // 函數(shù)function內(nèi)部代碼,將函數(shù)內(nèi)部代碼塊放入 try 節(jié)點
- isGenerator = node.generator,
- isAsync = node.async;
- // 創(chuàng)建 catch 節(jié)點中的代碼
- var catchStatement = template.statement(`ErrorCapture(error)`)();
- var catchClause = t.catchClause(t.identifier('error'),
- t.blockStatement(
- [catchStatement] // catchBody
- )
- );
- // 創(chuàng)建 try/catch 的 ast
- var ttryStatement = t.tryStatement(blockStatement, catchClause);
- + // 創(chuàng)建新節(jié)點
- + var func = t.functionExpression(node.id, params, t.BlockStatement([tryStatement]), isGenerator, isAsync);
- + // 打印看看是否成功
- + console.log('當前節(jié)點是:', func);
- + console.log('當前節(jié)點下的自節(jié)點是:', func.body);
- }
- });
此時將上述代碼在終端執(zhí)行 node src/index.js:
可以看到此時我們在一個函數(shù)表達式 body 中創(chuàng)建了一個 try 函數(shù)(TryStatement)。
最后我們需要將原函數(shù)節(jié)點進行替換:
- const parser = require("@babel/parser");
- const traverse = require("babel-traverse").default;
- const t = require("babel-types");
- const template = require("@babel/template");
- // 0、定義一個待處理的函數(shù)(mock)
- let source = `var fn = function() {...
- // 1、解析
- let ast = parser.parse(source, {...
- // 2、遍歷
- traverse(ast, {
- FunctionExpression(path, state) { // Function 節(jié)點
- var node = path.node,
- params = node.params,
- blockStatement = node.body, // 函數(shù)function內(nèi)部代碼,將函數(shù)內(nèi)部代碼塊放入 try 節(jié)點
- isGenerator = node.generator,
- isAsync = node.async;
- // 創(chuàng)建 catch 節(jié)點中的代碼
- var catchStatement = template.statement(`ErrorCapture(error)`)();
- var catchClause = t.catchClause(t.identifier('error'),...
- // 創(chuàng)建 try/catch 的 ast
- var ttryStatement = t.tryStatement(blockStatement, catchClause);
- // 創(chuàng)建新節(jié)點
- var func = t.functionExpression(node.id, params, t.BlockStatement([tryStatement]), isGenerator, isAsync);
- + // 替換原節(jié)點
- + path.replaceWith(func);
- }
- });
- + // 將新生成的 AST,轉(zhuǎn)為 Source 源碼:
- + return core.transformFromAstSync(ast, null, {
- + configFile: false // 屏蔽 babel.config.js,否則會注入 polyfill 使得調(diào)試變得困難
- + }).code;
“A loader is a node module exporting a function”,也就是說一個 loader 就是一個暴露出去的 node 模塊,既然是一個node module,也就基本可以寫成下面的樣子:
- module.exports = function() {
- // ...
- };
再編輯 src/index.js 為如下截圖:
邊界條件處理
我們并不需要為所有的函數(shù)都增加 try/catch,所有我們還得處理一些邊界條件。
- 1、如果有 try catch 包裹了
- 2、防止 circle loops
- 3、需要 try catch 的只能是語句,像 () => 0 這種的 body
- 4、如果函數(shù)內(nèi)容小于多少行數(shù)
滿足以上條件就 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 平臺 使用。
由于篇幅過長不易閱讀,本文特別的省略了本地調(diào)試過程,所以需要調(diào)試請移步 [【利用AST自動為函數(shù)增加錯誤上報-續(xù)集】有關(guān) npm 包的本地開發(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",
- ]
- }]
效果見如下圖所示: