rewiremock
Version:
Advanced dependency mocking device.
228 lines (175 loc) • 7.17 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.processFile = exports.readAliases = undefined;
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
var _getIterator2 = require('babel-runtime/core-js/get-iterator');
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _path = require('path');
var _executor = require('../../executor');
var _utils = require('./utils');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_CONFIG_NAMES = ['webpack.config.js', 'webpack.config.babel.js'];
// most of this file is a copypaste from https://github.com/trayio/babel-plugin-webpack-alias/blob/master/src/index.js
// just cos we emulate its behavior
function getConfigPath(configPaths) {
// Try all config paths and return for the first found one
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (0, _getIterator3.default)(configPaths), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var configPath = _step.value;
if (!configPath) continue;
var resolvedConfigPath = (0, _path.resolve)(process.cwd(), configPath);
var resolvedName = (0, _utils.fileExists)(resolvedConfigPath);
if (resolvedConfigPath && resolvedName) {
return resolvedName;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return null;
}
function readAliases(configPath) {
var configPaths = configPath ? [configPath].concat(DEFAULT_CONFIG_NAMES) : DEFAULT_CONFIG_NAMES;
// Get webpack config
var confPath = getConfigPath(configPaths);
// If the config comes back as null, we didn't find it, so throw an exception.
if (!confPath) {
throw new Error('Cannot find any of these configuration files: ' + configPaths.join(', '));
}
// Require the config
var conf = (0, _executor.requireModule)(confPath);
if (conf && conf.__esModule && conf.default) {
conf = conf.default;
}
// exit if there's no alias config and the config is not an array
if (!(conf.resolve && conf.resolve.alias) && !Array.isArray(conf)) {
throw new Error('The resolved config file doesn\'t contain a resolve configuration');
}
// Get the webpack alias config
var aliasConf = void 0;
var extensionsConf = void 0;
if (Array.isArray(conf)) {
// the exported webpack config is an array ...
// (i.e., the project is using webpack's multicompile feature) ...
// reduce the configs to a single alias object
aliasConf = conf.reduce(function (prev, curr) {
var next = (0, _assign2.default)({}, prev);
if (curr.resolve && curr.resolve.alias) {
(0, _assign2.default)(next, curr.resolve.alias);
}
return next;
}, {});
// if the object is empty, bail
if (!(0, _keys2.default)(aliasConf).length) {
return;
}
// reduce the configs to a single extensions array
extensionsConf = conf.reduce(function (prev, curr) {
var next = [].concat(prev);
if (curr.resolve && curr.resolve.extensions && curr.resolve.extensions.length) {
curr.resolve.extensions.forEach(function (ext) {
if (next.indexOf(ext) === -1) {
next.push(ext);
}
});
}
return next;
}, []);
if (!extensionsConf.length) {
extensionsConf = null;
}
} else {
// the exported webpack config is a single object...
// use it's resolve.alias property
aliasConf = conf.resolve.alias;
// use it's resolve.extensions property, if available
extensionsConf = conf.resolve.extensions && conf.resolve.extensions.length ? conf.resolve.extensions : null;
}
if (typeof __webpack_modules__ !== 'undefined') (0, _keys2.default)(aliasConf).forEach(function (alias) {
var location = aliasConf[alias];
if (!__webpack_modules__[location]) {
aliasConf[alias] = '.' + (0, _path.resolve)((0, _path.dirname)(confPath), '.' + location);
}
});
return {
aliasConf: aliasConf,
extensionsConf: extensionsConf
};
}
function processFile(filePath, _ref) {
var aliasConf = _ref.aliasConf,
extensionsConf = _ref.extensionsConf;
for (var aliasFrom in aliasConf) {
if (aliasConf.hasOwnProperty(aliasFrom)) {
var aliasTo = aliasConf[aliasFrom];
var regex = new RegExp('^' + aliasFrom + '(/|$)');
// If the regex matches, replace by the right config
if (regex.test(filePath)) {
// notModuleRegExp from https://github.com/webpack/enhanced-resolve/blob/master/lib/Resolver.js
/* eslint-disable no-useless-escape */
var notModuleRegExp = /^\.$|^\.[\\\/]|^\.\.$|^\.\.[\/\\]|^\/|^[A-Z]:[\\\/]/i;
var isModule = !notModuleRegExp.test(aliasTo);
if (isModule) {
return aliasTo;
}
// If the filepath is not absolute, make it absolute
if (!(0, _path.isAbsolute)(aliasTo)) {
aliasTo = (0, _path.join)(process.cwd(), aliasTo);
}
var relativeFilePath = (0, _path.resolve)((0, _path.dirname)(filePath), aliasTo).split(_path.sep).join('/');
// In case the file path is the root of the alias, need to put a dot to avoid having an absolute path
if (relativeFilePath.length === 0) {
relativeFilePath = '.';
}
var requiredFilePath = filePath.replace(aliasFrom, relativeFilePath);
// In the unfortunate case of a file requiring the current directory which is the alias, we need to add
// an extra slash
if (requiredFilePath === '.') {
requiredFilePath = './';
}
// In the case of a file requiring a child directory of the current directory, we need to add a dot slash
if (['.', '/'].indexOf(requiredFilePath[0]) === -1) {
requiredFilePath = './' + requiredFilePath;
}
// In case the extension option is passed
if (extensionsConf) {
(function () {
// Get an absolute path to the file
var absoluteRequire = (0, _path.join)(aliasTo, (0, _path.basename)(filePath));
var extension = extensionsConf.find(function (ext) {
if (!ext) return false;
// If the file with this extension exists set it
if ((0, _utils.fileExists)(absoluteRequire + ext)) {
return true;
}
});
// Set the extension to the file path, or keep the original one
requiredFilePath += extension || '';
})();
}
return requiredFilePath;
}
}
}
}
exports.readAliases = readAliases;
exports.processFile = processFile;