Fix custom require's (#4766)

This commit is contained in:
Lucas Duailibe authored and GitHub committed 2018-06-28 15:56:25 -03:00
1 parent 0ce40b197d
commit 576e570711
2 files changed
+48 -34

No files matched your search

@@ -2,32 +2,40 @@
//
// BEFORE:
// $$$r("path/to/file")
// eval("require")("./path/to/file")
// eval("require")(identifier)
//
// AFTER:
// require("./file")
// require(identifier)
//
module.exports = function(babel) {
const t = babel.types;
return {
visitor: {
CallExpression: function(path) {
CallExpression(path) {
const node = path.node;
if (
path.get("callee").isIdentifier({ name: "$$$r" }) &&
node.arguments.length === 1 &&
path.get("arguments.0").isStringLiteral()
) {
const value = node.arguments[0].value;
const parts = value.split("/");
path.replaceWith(
t.callExpression(t.identifier("require"), [
t.stringLiteral(`./${parts[parts.length - 1]}`)
])
);
if (isEvalRequire(node)) {
let arg = node.arguments[0];
if (t.isLiteral(arg) && arg.value.startsWith(".")) {
const value = "." + arg.value.substring(arg.value.lastIndexOf("/"));
arg = t.stringLiteral(value);
}
path.replaceWith(t.callExpression(t.identifier("require"), [arg]));
}
}
}
};
function isEvalRequire(node) {
return (
t.isCallExpression(node.callee) &&
node.arguments.length === 1 &&
t.isIdentifier(node.callee.callee, { name: "eval" }) &&
node.callee.arguments.length === 1 &&
t.isLiteral(node.callee.arguments[0], { value: "require" })
);
}
};