UNPKG

@uiw/babel-plugin-add-import-extension

Version:

Remove the specified import declaration when you use the babel transform to build the package.

158 lines (151 loc) 8.8 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports.makeDeclaration = exports.isNodeModule = exports["default"] = void 0; var _helperPluginUtils = require("@babel/helper-plugin-utils"); var _fs = require("fs"); var _path = require("path"); var _core = require("@babel/core"); function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } var importDeclaration = _core.types.importDeclaration, exportNamedDeclaration = _core.types.exportNamedDeclaration, exportAllDeclaration = _core.types.exportAllDeclaration, stringLiteral = _core.types.stringLiteral; // Checks if the module has an active extension var isActiveExtension = function isActiveExtension(module, observedScriptExtensions) { var ext = (0, _path.extname)(module).toLowerCase().replace(/[^a-z]/, ''); return observedScriptExtensions.includes(ext); }; // Checks if the module is a Node module var isNodeModule = exports.isNodeModule = function isNodeModule(module) { if (module.startsWith('.') || module.startsWith('/')) { return false; } try { require.resolve(module); return true; } catch (e) { if (e.code === 'MODULE_NOT_FOUND') { return false; } // console.error(e); } }; var skipModule = function skipModule(module, _ref) { var replace = _ref.replace, extension = _ref.extension, skipUnlistedExtensions = _ref.skipUnlistedExtensions, observedScriptExtensions = _ref.observedScriptExtensions; // If the module path does not start with "." (not a relative path) or is a Node module, skip it directly if (!module.startsWith('.') || isNodeModule(module)) { return true; } // Get the module's extension and convert it to lowercase var moduleExtension = (0, _path.extname)(module).toLowerCase(); var moduleExtensionWithoutDot = moduleExtension.replace(/^\./, ''); // If the module's extension is not in the list of observed script extensions, skip it if (skipUnlistedExtensions == true && moduleExtension != "" && !observedScriptExtensions.includes(moduleExtensionWithoutDot)) { return true; } // If the module has no extension, do not skip it (because an extension might need to be added) if (!moduleExtension) { return false; } // If the module already has the target extension (after converting to lowercase), skip it if (moduleExtension === ".".concat(extension.toLowerCase())) { return true; } // When replace is true, allow replacing the existing extension, so do not skip if (replace) { return false; // Do not skip, allow replacing the extension } // When replace is false, skip if the module has an "active" extension return isActiveExtension(module, observedScriptExtensions); }; // Generates a module path declaration var makeDeclaration = exports.makeDeclaration = function makeDeclaration(_ref2) { var declaration = _ref2.declaration, args = _ref2.args; return function (path, state) { var node = path.node; var source = node.source, exportKind = node.exportKind, importKind = node.importKind; var _state$opts = state.opts, _state$opts$replace = _state$opts.replace, replace = _state$opts$replace === void 0 ? false : _state$opts$replace, _state$opts$extension = _state$opts.extension, extension = _state$opts$extension === void 0 ? 'js' : _state$opts$extension, _state$opts$skipUnlis = _state$opts.skipUnlistedExtensions, skipUnlistedExtensions = _state$opts$skipUnlis === void 0 ? false : _state$opts$skipUnlis, _state$opts$observedS = _state$opts.observedScriptExtensions, observedScriptExtensions = _state$opts$observedS === void 0 ? ['js', 'ts', 'jsx', 'tsx', 'mjs', 'cjs'] : _state$opts$observedS; // If there is no source or it's a type-only import/export, return directly var isTypeOnly = exportKind === 'type' || importKind === 'type'; if (!source || isTypeOnly) return; var module = source.value; // If the module should be skipped, return directly if (skipModule(module, { replace: replace, extension: extension, skipUnlistedExtensions: skipUnlistedExtensions, observedScriptExtensions: observedScriptExtensions })) return; var dirPath = (0, _path.resolve)((0, _path.dirname)(module), module); var hasModuleExt = (0, _path.extname)(module).length && isActiveExtension(module, observedScriptExtensions); var newModuleName = hasModuleExt ? module.slice(0, -(0, _path.extname)(module).length) : module; // Generates the new path based on the module path var pathLiteral = function pathLiteral() { if ((0, _fs.existsSync)(dirPath) && (0, _fs.lstatSync)(dirPath).isDirectory()) { return "".concat(module).concat(newModuleName.endsWith('/') ? '' : '/', "index.").concat(extension); } if (newModuleName.endsWith('/')) { newModuleName = "".concat(module, "index"); } return "".concat(newModuleName, ".").concat(extension); }; path.replaceWith(declaration.apply(void 0, _toConsumableArray(args(path)).concat([stringLiteral(pathLiteral())]))); }; }; var _default = exports["default"] = (0, _helperPluginUtils.declare)(function (api, options) { api.assertVersion(7); return { name: 'add-import-extension', visitor: { ImportDeclaration: makeDeclaration(_objectSpread(_objectSpread({}, options), {}, { declaration: importDeclaration, args: function args(_ref3) { var specifiers = _ref3.node.specifiers; return [specifiers]; } })), ExportNamedDeclaration: makeDeclaration(_objectSpread(_objectSpread({}, options), {}, { declaration: exportNamedDeclaration, args: function args(_ref4) { var _ref4$node = _ref4.node, declaration = _ref4$node.declaration, specifiers = _ref4$node.specifiers; return [declaration, specifiers]; } })), ExportAllDeclaration: makeDeclaration(_objectSpread(_objectSpread({}, options), {}, { declaration: exportAllDeclaration, args: function args() { return []; } })) } }; });