babel-plugin-import-redirect
Version:
Import, export, require path redirect plugin for Babel
58 lines (46 loc) • 2.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (t, path, state, calculatedOpts) {
var callee = path.node.callee,
functionNames = calculatedOpts.functionNames;
if (t.isIdentifier(callee) && functionNames.has(callee.name) || t.isImport(callee) ||
// don't check further if there is only "require" in functionNames
functionNames.size > 1 && t.isMemberExpression(callee) && functionNames.has(membToString(t, callee))) {
var pathToMatch = path.get("arguments.0"),
pathToRemove = path.parentPath.isExpressionStatement() && path.parentPath;
if (pathToMatch.isStringLiteral()) {
(0, _replacePath2.default)(t, {
pathToMatch: pathToMatch,
pathToRemove: pathToRemove,
pathToReplace: !pathToRemove && path,
replaceFn: replaceRequire
}, calculatedOpts, state);
}
}
};
var _replacePath = require("../helpers/replacePath");
var _replacePath2 = _interopRequireDefault(_replacePath);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var membToString = function membToString(t, _ref) {
var object = _ref.object,
property = _ref.property,
computed = _ref.computed;
var propIsIdentifier = t.isIdentifier(property);
if (!object.name || computed && propIsIdentifier) return null;
return object.name + "." + (propIsIdentifier ? property.name : property.value);
};
var replaceRequire = function replaceRequire(t, replacementObj, pathToReplace, wrapReplacementInPromise) {
var node = pathToReplace.node,
callee = pathToReplace.node.callee;
if (t.isImport(callee) || t.isIdentifier(callee) && wrapReplacementInPromise.has(callee.name) ||
// don't check further if there nothing in wrapReplacementInPromise
wrapReplacementInPromise.size > 0 && t.isMemberExpression(callee) && wrapReplacementInPromise.has(membToString(t, callee))) {
var promise = t.memberExpression(t.identifier("Promise"), t.identifier("resolve"));
replacementObj = t.callExpression(promise, [replacementObj]);
} else if (pathToReplace.parentPath.isMemberExpression({ object: node })) {
replacementObj = t.parenthesizedExpression(replacementObj);
}
pathToReplace.replaceWith(replacementObj);
};