UNPKG

babel-plugin-remove-unused-import

Version:
84 lines (73 loc) 3.38 kB
'use strict'; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); /** * @file: index * @author: Cuttle Cong * @date: 2017/11/29 * @description: */ var match = require('./utils/matchRule'); module.exports = function (babel) { var t = babel.types; return { visitor: { Program: { exit: function exit(path) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, opts = _ref.opts; var UnRefBindings = new Map(); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.entries(path.scope.bindings)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _step$value = _slicedToArray(_step.value, 2), name = _step$value[0], binding = _step$value[1]; if (!binding.path.parentPath || binding.kind !== 'module') continue; var source = binding.path.parentPath.get('source'); var importName = source.node.value; if (!t.isStringLiteral(source) || opts.ignore && match(opts.ignore, importName)) continue; var key = importName + '(' + (source.node.loc && source.node.loc.start.line) + ')'; if (!UnRefBindings.has(key)) { UnRefBindings.set(key, binding); } if (binding.referenced) { UnRefBindings.set(key, null); } else { var nodeType = binding.path.node.type; if (nodeType === 'ImportSpecifier') { binding.path.remove(); } else if (nodeType === 'ImportDefaultSpecifier') { binding.path.remove(); } else if (nodeType === 'ImportNamespaceSpecifier') { binding.path.remove(); } else if (binding.path.parentPath) { binding.path.parentPath.remove(); } } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } UnRefBindings.forEach(function (binding, key) { if (binding && binding.path.parentPath) { binding.path.parentPath.remove(); } }); } } } }; };