Last active
November 2, 2022 06:32
-
-
Save phuctm97/7470a3b981fd80a501b4047e1e99a9f4 to your computer and use it in GitHub Desktop.
π Get Webpack alias from tsconfig.json, aka. convert tsconfig.json paths to Webpack alias
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
const path = require('path'); | |
/** | |
* Helper function infers Webpack aliases from tsconfig.json compilerOptions.baseUrl and | |
* compilerOptions.paths. | |
* | |
* @param {string} tsconfigPath - Path to tsconfig.json (can be either relative or absolute path). | |
* @return {object} An object representing analogous Webpack alias. | |
*/ | |
module.exports = (tsconfigPath = './tsconfig.json') => { | |
const tsconfig = require(tsconfigPath); | |
const { paths, baseUrl } = tsconfig.compilerOptions; | |
return Object.fromEntries(Object.entries(paths) | |
.filter(([, pathValues]) => pathValues.length > 0) | |
.map(([pathKey, pathValues]) => { | |
const key = pathKey.replace('/*', ''); | |
const value = path.resolve(path.dirname(tsconfigPath), | |
baseUrl, pathValues[0].replace('/*', '')); | |
return [key, value]; | |
})); | |
}; |
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
Show hidden characters
{ | |
"compilerOptions": { | |
"baseUrl": ".", | |
"paths": { | |
"@core/*": ["src/core/*"], | |
"@util/*": ["src/util/*"] | |
} | |
} | |
} |
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
const path = require('path'); | |
const getAlias = require('./get-webpack-alias-from-tsconfig'); | |
module.exports = { | |
resolve: { | |
alias: getAlias(path.resolve(__dirname, 'tsconfig.json')), | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment