Skip to content

Instantly share code, notes, and snippets.

@phuctm97
Last active November 2, 2022 06:32
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save phuctm97/7470a3b981fd80a501b4047e1e99a9f4 to your computer and use it in GitHub Desktop.
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
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];
}));
};
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@core/*": ["src/core/*"],
"@util/*": ["src/util/*"]
}
}
}
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