Last active
March 26, 2025 13:00
-
-
Save nerdyman/2f97b24ab826623bff9202750013f99e to your computer and use it in GitHub Desktop.
Convert TypeScript tsconfig paths to webpack alias paths
This file contains hidden or 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 { resolve } = require('path'); | |
/** | |
* Resolve tsconfig.json paths to Webpack aliases | |
* @param {string} tsconfigPath - Path to tsconfig | |
* @param {string} webpackConfigBasePath - Path from tsconfig to Webpack config to create absolute aliases | |
* @return {object} - Webpack alias config | |
*/ | |
function resolveTsconfigPathsToAlias({ | |
tsconfigPath = './tsconfig.json', | |
webpackConfigBasePath = __dirname, | |
} = {}) { | |
const { paths } = require(tsconfigPath).compilerOptions; | |
const aliases = {}; | |
Object.keys(paths).forEach((item) => { | |
const key = item.replace('/*', ''); | |
const value = resolve(webpackConfigBasePath, paths[item][0].replace('/*', '').replace('*', '')); | |
aliases[key] = value; | |
}); | |
return aliases; | |
} | |
module.exports = resolveTsconfigPathsToAlias; |
This file contains hidden or 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
{ | |
"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": { | |
"Root/*": ["src/*"], | |
"Components/*": ["src/components/*"], | |
"Data/*": ["src/data/*"], | |
} | |
}, |
This file contains hidden or 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
import Banner from 'Components/banner'; |
This file contains hidden or 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
// 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 | |
}), | |
} | |
} |
@its-dibo moved more specific first in the tsconfig paths as a workaround...
Hi!
There will be an error if the file does not have the 'paths' section
- [webpack-cli] TypeError: Cannot convert undefined or null to object
There will be an error if there is an extra comma or comment
- [webpack-cli] SyntaxError: tsconfig.json: Unexpected token ']', ..."*",},
"... is not valid JSON
Here is the solution. I'll leave it here, maybe someone will find it useful.
// tsconfig.json
{
"compilerOptions": {
// comment
"paths": {
"Root/*": ["src/*",],
"Components/*": ["src/components/*",],
"Data/*": ["src/data/*",],
}
},
}
// tsconfig-paths.mjs
import { dirname, resolve } from 'node:path';
import ts from 'typescript';
/** @typedef {Record<"compilerOptions", ts.server.protocol.CompilerOptions>} CompilerOptions */
const tsParsedCmd =
/** @type {Record<"raw", CompilerOptions>} */
(
ts.getParsedCommandLineOfConfigFile('tsconfig.json', undefined, {
...ts.sys,
onUnRecoverableConfigFileDiagnostic(diagnostic) {
throw new Error(`${diagnostic.messageText}`);
},
})
);
export function tsconfigPaths() {
const res = /** @type {ts.MapLike<string[]>} */ ({});
const { paths } = tsParsedCmd.raw.compilerOptions;
if (paths) {
for (const k of Object.keys(paths)) {
const val = paths[k];
res[dirname(k)] = val.map((path) => {
return resolve(process.cwd(), dirname(path));
});
}
}
return res;
}
// webpack.config.mjs
/** @type {import("webpack").Configuration} */
export default {
resolve: {
alias: tsconfigPaths(),
},
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
there is an issue in this configuration, because the first matched alias is selected instead of the most specific one