UNPKG

babel-plugin-transform-import-paths

Version:
61 lines (60 loc) 2.17 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformPath = exports.withoutRootPathPrefix = exports.isRootPath = exports.hasPrefix = exports.getPath = exports.getArg = void 0; const path_1 = __importDefault(require("path")); const slash_1 = __importDefault(require("slash")); function getArg(t, arg) { if (t.isStringLiteral(arg)) { return arg; } if (t.isBinaryExpression(arg)) { return getArg(t, arg.left); } return; } exports.getArg = getArg; function getPath(importPath, options = {}, sourceFile = '') { for (let prop in options) { if (hasPrefix(prop, importPath)) { return transformPath(importPath, prop, options[prop], slash_1.default(sourceFile)); } } } exports.getPath = getPath; function hasPrefix(prefix, importPath = '') { if (importPath.substring(0, prefix.length) === prefix) { return true; } if (importPath.substring(0, prefix.length + 1) === `${prefix}/`) { return true; } return false; } exports.hasPrefix = hasPrefix; function isRootPath(importPath) { return (importPath.substring(0, 1) === '/') ? true : false; } exports.isRootPath = isRootPath; function withoutRootPathPrefix(importPath) { return isRootPath(importPath) ? importPath.substring(1, importPath.length) : importPath; } exports.withoutRootPathPrefix = withoutRootPathPrefix; function transformPath(importPath, prop, value, sourceFile = '') { let replacedPath = importPath.replace(prop, value); let absolutePath = path_1.default.resolve(`./${replacedPath}`); let sourcePath = sourceFile.substring(0, sourceFile.lastIndexOf('/')); let relativePath = slash_1.default(path_1.default.relative(sourcePath, absolutePath)); if (relativePath.indexOf('../') !== 0) { relativePath = './' + relativePath; } if (importPath[importPath.length - 1] === '/') { relativePath += '/'; } return relativePath; } exports.transformPath = transformPath;