Created
February 27, 2023 22:32
-
-
Save ElMassimo/9ee7c89d0016879b127cb80c6dc9187d to your computer and use it in GitHub Desktop.
How to configure resolve.alias by using paths in tsconfig.json
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
import { defineConfig, type AliasOptions } from 'vite' | |
import { readFileSync } from 'fs' | |
import { parse as parseJSON } from 'json5' | |
import { resolve } from 'path' | |
import { projectRoot } from 'vite-plugin-ruby' | |
/** | |
* Makes it possible to use shorter absolute path references, which are not | |
* ambiguous, and easier to refactor than relative paths. | |
*/ | |
const tsConfigAlias: AliasOptions = {} | |
Object.entries(tsConfigPaths(resolve(projectRoot, 'tsconfig.json'))).forEach(([importPath, [actualPath]]) => { | |
// In Rollup aliases, we want to skip the `*` glob that is used in tsconfig. | |
const suffix = actualPath.endsWith('/*') ? '/' : '' | |
tsConfigAlias[importPath.replace('*', '')] = resolve(projectRoot, actualPath.replace('/*', '')) + suffix | |
}) | |
// Helper: Returns the path aliases in tsconfig.json. | |
function tsConfigPaths(tsConfigFile: string) { | |
const tsConfig = parseJSON(readFileSync(tsConfigFile, 'utf8')) | |
return tsConfig.compilerOptions.paths as Record<string, [string]> | |
} | |
export default defineConfig({ | |
resolve: { | |
alias: { | |
...tsConfigAlias, | |
}, | |
}, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment