UNPKG

babel-plugin-root-import

Version:
61 lines (41 loc) 2.16 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformRelativeToRootPath = exports.hasRootPathPrefixInString = undefined; var _slash = require('slash'); var _slash2 = _interopRequireDefault(_slash); var _path = require('path'); var _path2 = _interopRequireDefault(_path); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var defaultRoot = (0, _slash2.default)(global.rootPath || process.cwd()); var hasRootPathPrefixInString = exports.hasRootPathPrefixInString = function hasRootPathPrefixInString(importPath) { var rootPathPrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '~'; return !!(typeof importPath === 'string' && importPath.indexOf(rootPathPrefix) === 0); }; var transformRelativeToRootPath = exports.transformRelativeToRootPath = function transformRelativeToRootPath(importPath, rootPathSuffix, rootPathPrefix) { var _sourceFile = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; var _root = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : defaultRoot; var sourceFile = (0, _slash2.default)(_sourceFile); if (hasRootPathPrefixInString(importPath, rootPathPrefix)) { var withoutRootPathPrefix = importPath.replace(rootPathPrefix, ''); var suffix = rootPathSuffix ? rootPathSuffix : './'; var root = typeof _root === 'function' ? _root(sourceFile) : _root; var absolutePath = _path2.default.resolve(root, suffix + '/' + withoutRootPathPrefix); var sourcePath = sourceFile.substring(0, sourceFile.lastIndexOf('/')); var relativePath = _path2.default.relative(_path2.default.resolve(sourcePath), absolutePath).replace(/\\/g, '/'); // if file is located in the same folder if (relativePath.indexOf('../') !== 0) { relativePath = './' + relativePath; } // if the entry has a slash, keep it if (importPath[importPath.length - 1] === '/') { relativePath += '/'; } return relativePath; } if (typeof importPath === 'string') { return importPath; } throw new Error('ERROR: No path passed'); };