jsconfig-paths-jest-mapper
Version:
Use this to load modules whose location is specified in the `paths` section of `jsconfig.json` when using jest.
36 lines (31 loc) • 1.06 kB
JavaScript
const path = require('path');
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function readConfigFile(configPath) {
let config = null;
try {
config = require(configPath);
} catch (err) {
console.log(err);
process.exit(1);
}
return config;
}
function PathJestMapper(options = {}) {
this.context = options.context ? path.resolve(options.context) : process.cwd();
this.configFilePath = path.join(this.context, (options.configFileName || 'jsconfig.json'));
this.config = readConfigFile(this.configFilePath);
this.options = this.config.compilerOptions;
return this.resolve();
}
PathJestMapper.prototype.resolve = function() {
const { baseUrl, paths } = this.options;
const mappedPaths = {};
Object.keys(paths).forEach((alias) => {
const pattern = `^${escapeRegExp(alias).replace('\\*', '(.*)')}$`;
mappedPaths[pattern] = path.join('<rootDir>' ,baseUrl, paths[alias][0]).replace('\*', '$1');
});
return mappedPaths;
}
module.exports = PathJestMapper;