@bestcodetools/jest-tsconfig-paths-mapper
Version:
A utility library for generating Jest's moduleNameMapper based on TypeScript's tsconfig.json path mappings.
30 lines (22 loc) • 951 B
JavaScript
const fs = require('fs');
const path = require('path');
function transformPathsToModuleNameMapper(paths, baseUrl) {
const moduleNameMapper = {};
for (const [key, value] of Object.entries(paths)) {
const modulePath = key.replace('/*', '/(.*)').replace(/([$]|[#]|[>]|[:]|[!]|[`]|[´]|[?]|[%]|[&])/g, '[$1]');
const moduleReplacement = value[0].replace('/*', '/$1');
const regex = new RegExp(`^${modulePath}$`);
moduleNameMapper[regex.source] = path.resolve(baseUrl, moduleReplacement);
}
return moduleNameMapper;
}
function generateModuleNameMapper(tsconfigPath = 'tsconfig.json') {
const tsconfigContent = fs.readFileSync(tsconfigPath, 'utf-8');
const tsconfig = eval(`(() => (\n${tsconfigContent}\n))()`);
const { paths, baseUrl } = tsconfig.compilerOptions;
const moduleNameMapper = transformPathsToModuleNameMapper(paths, baseUrl);
return moduleNameMapper;
}
module.exports = {
generateModuleNameMapper
};