const core = require('@babel/core');
const types = require('babel-types');
const template = require('@babel/template');
const sourceCode = `
function sum(a,b) {
return a+b+c;
}
`;
let tryStatementPlugin = {
visitor: {
FunctionDeclaration(nodePath) {
let { node } = nodePath;
let { id } = node;
let nodeStatement = node.body;
if (nodeStatement && types.isTryStatement(nodeStatement.body[0])) return;
let catchStatement = template.statement('console.log(error)')();
let catchClause = types.catchClause(
types.identifier('error'),
types.blockStatement([catchStatement])
);
let tryStatement = types.tryStatement(node.body, catchClause);
var func = types.functionExpression(
id,
node.params,
types.blockStatement([tryStatement]),
node.generator,
node.async
);
nodePath.replaceWith(func);
},
},
};
const targetCode = core.transform(sourceCode, {
plugins: [tryStatementPlugin],
});
console.log(targetCode.code);
网友评论