Files
test-repo/scripts/build/babel-plugins/transform-custom-require.js
T

55 lines
1.3 KiB
JavaScript
Raw Normal View History

2018-05-24 15:30:45 -03:00
"use strict";
//
// BEFORE:
2018-06-28 15:56:25 -03:00
// eval("require")("./path/to/file")
// eval("require")(identifier)
// eval("require").cache
2018-05-24 15:30:45 -03:00
//
// AFTER:
// require("./file")
2018-06-28 15:56:25 -03:00
// require(identifier)
// require.cache
2018-05-24 15:30:45 -03:00
//
module.exports = function(babel) {
const t = babel.types;
2018-06-28 15:56:25 -03:00
2018-05-24 15:30:45 -03:00
return {
visitor: {
2018-06-28 15:56:25 -03:00
CallExpression(path) {
2020-01-14 23:30:18 +08:00
const { node } = path;
if (isEvalRequire(node.callee) && node.arguments.length === 1) {
2018-06-28 15:56:25 -03:00
let arg = node.arguments[0];
if (t.isLiteral(arg) && arg.value.startsWith(".")) {
2020-01-23 20:15:28 +08:00
const value = "." + arg.value.slice(arg.value.lastIndexOf("/"));
2018-06-28 15:56:25 -03:00
arg = t.stringLiteral(value);
}
path.replaceWith(t.callExpression(t.identifier("require"), [arg]));
2018-05-24 15:30:45 -03:00
}
},
MemberExpression(path) {
2020-01-14 23:30:18 +08:00
const { node } = path;
if (isEvalRequire(node.object)) {
path.replaceWith(
t.memberExpression(
t.identifier("require"),
node.property,
node.compute,
node.optional
)
);
}
2018-05-24 15:30:45 -03:00
}
}
};
2018-06-28 15:56:25 -03:00
function isEvalRequire(node) {
return (
t.isCallExpression(node) &&
t.isIdentifier(node.callee, { name: "eval" }) &&
2018-06-28 15:56:25 -03:00
node.arguments.length === 1 &&
t.isLiteral(node.arguments[0], { value: "require" })
2018-06-28 15:56:25 -03:00
);
}
2018-05-24 15:30:45 -03:00
};