Build: Simplify transform-custom-require plugin (#8735)

This commit is contained in:
fisker Cheung authored and GitHub committed 2020-07-20 18:35:28 +08:00
1 parent 736f98f9a6
commit 8c00ad44df
2 files changed
+8 -43

No files matched your search

@@ -1,16 +1,6 @@
"use strict";
//
// BEFORE:
// eval("require")("./path/to/file")
// eval("require")(identifier)
// eval("require").cache
//
// AFTER:
// require("./file")
// require(identifier)
// require.cache
//
// `eval("require")` -> `require`
module.exports = function (babel) {
const t = babel.types;
@@ -19,37 +9,14 @@ module.exports = function (babel) {
visitor: {
CallExpression(path) {
const { node } = path;
if (isEvalRequire(node.callee) && node.arguments.length === 1) {
let arg = node.arguments[0];
if (t.isLiteral(arg) && arg.value.startsWith(".")) {
const value = "." + arg.value.slice(arg.value.lastIndexOf("/"));
arg = t.stringLiteral(value);
}
path.replaceWith(t.callExpression(t.identifier("require"), [arg]));
}
},
MemberExpression(path) {
const { node } = path;
if (isEvalRequire(node.object)) {
path.replaceWith(
t.memberExpression(
t.identifier("require"),
node.property,
node.compute,
node.optional
)
);
if (
t.isIdentifier(node.callee, { name: "eval" }) &&
node.arguments.length === 1 &&
t.isLiteral(node.arguments[0], { value: "require" })
) {
path.replaceWith(t.identifier("require"));
}
},
},
};
function isEvalRequire(node) {
return (
t.isCallExpression(node) &&
t.isIdentifier(node.callee, { name: "eval" }) &&
node.arguments.length === 1 &&
t.isLiteral(node.arguments[0], { value: "require" })
);
}
};
+1 -3
View File
@@ -1,8 +1,6 @@
"use strict";
// `/scripts/build/babel-plugins/transform-custom-require.js` doesn't support destructuring.
// eslint-disable-next-line prefer-destructuring
let resolve = eval("require").resolve;
let { resolve } = eval("require");
// In the VS Code and Atom extensions `require` is overridden and `require.resolve` doesn't support the 2nd argument.
if (resolve.length === 1 || process.env.PRETTIER_FALLBACK_RESOLVE) {