Last active
February 12, 2025 23:25
-
-
Save Salemsky/190b50776a58bc0b0723784a1ebe86a4 to your computer and use it in GitHub Desktop.
tsconfig paths to webpack
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 { dirname, resolve } from 'node:path'; | |
import ts from 'typescript'; | |
/** @typedef {Record<'compilerOptions', ts.server.protocol.CompilerOptions>} CompilerOptions */ | |
const parsedConfig = | |
/** @type {Record<'raw', CompilerOptions>} */ | |
( | |
ts.getParsedCommandLineOfConfigFile('tsconfig.json', undefined, { | |
...ts.sys, | |
onUnRecoverableConfigFileDiagnostic(diag) { | |
throw new Error(`${diag.messageText}`); | |
}, | |
}) | |
); | |
/** | |
* Retrieves the paths defined in the `paths` section of the `tsconfig.json` configuration file. | |
* @returns {ts.MapLike<string[]>} An object containing paths to various modules. An empty object if there is no `paths` section. | |
* @example | |
* ``` | |
* export default { | |
* resolve: { | |
* alias: tsconfigPaths(), | |
* }, | |
* } | |
* ``` | |
* | |
*/ | |
export function tsconfigPaths() { | |
const res = /** @type {ts.MapLike<string[]>} */ (Object.create(null)); | |
const { paths } = parsedConfig.raw.compilerOptions; | |
if (paths) { | |
for (const k in paths) { | |
const v = paths[k]; | |
res[k.endsWith('*') ? dirname(k) : k] = v.map((p) => { | |
return resolve(process.cwd(), dirname(p)); | |
}); | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment