-
-
Save alirezabonab/53eb12a246dea770ff94f16d21de4dc1 to your computer and use it in GitHub Desktop.
Jest + Typescript. Resolve tsconfig.json paths.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Converts paths defined in tsconfig.json to the format of | |
* moduleNameMapper in jest.config.js. | |
* | |
* For example, {'@alias/*': [ 'path/to/alias/*' ]} | |
* Becomes {'@alias/(.*)': [ '<rootDir>/path/to/alias/$1' ]} | |
* | |
* @param {string} srcPath | |
* @param {string} tsconfigPath | |
*/ | |
function makeModuleNameMapper(srcPath, tsconfigPath) { | |
// Get paths from tsconfig | |
const {paths} = require(tsconfigPath).compilerOptions; | |
const aliases = {}; | |
// Iterate over paths and convert them into moduleNameMapper format | |
Object.keys(paths).forEach((item) => { | |
const key = item.replace('/*', '/(.*)'); | |
const path = paths[item][0].replace('/*', '/$1'); | |
aliases[key] = srcPath + '/' + path; | |
}); | |
return aliases; | |
} | |
const TS_CONFIG_PATH = './tsconfig.json'; | |
const SRC_PATH = '<rootDir>/src'; | |
module.exports = { | |
'roots': [ | |
SRC_PATH | |
], | |
'transform': { | |
'^.+\\.tsx?$': 'ts-jest' | |
}, | |
'moduleNameMapper': makeModuleNameMapper(SRC_PATH, TS_CONFIG_PATH) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment