UNPKG

babel-plugin-import-redirect

Version:
75 lines (60 loc) 2.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (t, path, state, calculatedOpts) { var pathIsImportDeclaration = path.isImportDeclaration(); var pathToMatch = path.get("source"), pathToRemove = pathIsImportDeclaration && !path.node.specifiers.length && path, pathToReplace = pathIsImportDeclaration && path.node.specifiers.length && path; if (pathToMatch.node) { (0, _replacePath2.default)(t, { pathToMatch: pathToMatch, pathToRemove: pathToRemove, pathToReplace: pathToReplace, replaceFn: replaceImport }, calculatedOpts, state); } }; var _replacePath = require("../helpers/replacePath"); var _replacePath2 = _interopRequireDefault(_replacePath); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var replaceImport = function replaceImport(t, replacementObj, pathToReplace) { var props = []; var firstDeclaration = void 0, firstIdentifier = void 0; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = pathToReplace.node.specifiers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var specifier = _step.value; if (t.isImportNamespaceSpecifier(specifier)) { firstDeclaration = t.variableDeclarator(firstIdentifier = specifier.local, replacementObj); } else { var isDefaultSpecifier = t.isImportDefaultSpecifier(specifier); var imported = isDefaultSpecifier ? t.Identifier("default") : specifier.imported; var local = specifier.local; var shorthand = !isDefaultSpecifier && imported.start === local.start && imported.end === local.end; var objectProp = t.objectProperty(imported, specifier.local, false, shorthand); props.push(objectProp); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var declarations = firstDeclaration ? props.length ? [firstDeclaration, t.variableDeclarator(t.objectPattern(props, null), firstIdentifier)] : [firstDeclaration] : props.length ? [t.variableDeclarator(t.objectPattern(props), replacementObj)] : []; var variableDeclaration = t.variableDeclaration("const", declarations); pathToReplace.replaceWith(variableDeclaration); };