将箭头函数转化为普通函数
2024年11月10日
一、认识
二、实现
const jscodeshift = require("jscodeshift");
function transformArrowToFunction(sourceCode) {
const ast = jscodeshift(sourceCode);
const {
blockStatement,
returnStatement,
functionExpression,
ArrowFunctionExpression,
} = jscodeshift;
return ast
.find(ArrowFunctionExpression)
.replaceWith((path) => {
const { params, body, async } = path.node;
const functionBody =
body.type === "BlockStatement"
? body
: blockStatement([returnStatement(body)]);
return functionExpression(null, params, functionBody, false, async);
})
.toSource();
}
// 测试代码
const sourceCode = `const a = () => 1;`;
const result = transformArrowToFunction(sourceCode);
console.log(result);