我目前正在研究babeljs以及他们将代码从ESX转换为ES5的方式。
实际上,我正在尝试编写一个真正(非常)简单的插件来翻译一些简单的语句,并且在尝试转换箭头函数和返回语句时我被卡住了。
这是我想要传达的代码:
const x = () => null;
以下是我想要的内容:
var creatingAVariablex = function () {
return null;
};
从现在开始,我的插件中包含以下代码:
module.exports = function({ types: t }) {
return {
visitor: {
Identifier(path, state) {
path.node.name = "creatingAVariable" + path.node.name;
},
ArrowFunctionExpression(path) {
/**
* Here, I should transpile () => to function() {}
* special case: when path.node.expression, I have to add curly around the body + return statement
* I tried with the following stuff, but it seems that I'm missing something concerning the way
* I should create the functionExpression
*/
path.replaceWith(t.functionExpression(path.node.body));
},
VariableDeclaration(path) {
path.node.kind = "var";
}
}
};
};
我不知道从哪里开始,我无法找到API定义来创建functionExpression
。
有人知道我能处理这个案件的人吗?
编辑:我设法使其与
一起使用module.exports = function({ types: t }) {
return {
visitor: {
Identifier(path, state) {
path.node.name = "creatingAVariable" + path.node.name;
},
ArrowFunctionExpression(path) {
/**
* Here, I should transpile () => to function() {}
* special case: when path.node.expression, I have to add curly around the body + return statement
* I tried with the following stuff, but it seems that I'm missing something concerning the way
* I should create the functionExpression
*/
path.replaceWith(
t.functionExpression(
t.Identifier("func"),
[],
t.BlockStatement([t.returnStatement(path.node.body)])
)
);
},
VariableDeclaration(path) {
path.node.kind = "var";
}
}
};
};