Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agustinvinao/bfe717366c717df0693d9c94eaf300f8 to your computer and use it in GitHub Desktop.
Save agustinvinao/bfe717366c717df0693d9c94eaf300f8 to your computer and use it in GitHub Desktop.
Convert TypeScript tsconfig paths to webpack alias paths
const { resolve } = require('path');
/**
* Resolve tsconfig.json paths to Webpack aliases
* @param {string} tsconfigPath - Path to tsconfig
* @param {string} webpackConfigBasePath - Relative base path from tsconfig to Webpack config to create absolute aliases
* @return {object} - Webpack alias config
*/
function resolveTsconfigPathsToAlias({
tsconfigPath = './tsconfig.json',
webpackConfigBasePath = './'} = {},
) {
const { paths } = require(tsconfigPath).compilerOptions;
const aliases = {};
Object.keys(paths).forEach((item) => {
const key = item.replace('/*', '');
const value = resolve(webpackConfigBasePath, paths[item][0].replace('/*', ''));
aliases[key] = value;
});
return aliases;
}
module.exports = resolveTsconfigPathsToAlias;
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./dist",
"allowJs": true,
"target": "es6",
"jsx": "react",
"sourceMap": true,
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "./",
"lib": [
"DOM",
"ES5",
"ES6",
"es2017.object"
],
"paths": {
"Components/*": ["src/components/*"],
"Data/*": ["src/data/*"],
}
},
import Banner from 'Components/banner';
// add paths to webpack
const resolveTsconfigPathsToAlias = require('./resolve-tsconfig-path-to-webpack-alias');
module.exports = {
// ...
resolve: {
// ...
alias: resolveTsconfigPathsToAlias({
tsconfigPath: '../tsconfig.json', // Using custom path
webpackConfigBasePath: '../', // Using custom path
}),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment