Skip to content

Instantly share code, notes, and snippets.

@ElMassimo
Created February 27, 2023 22:32
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 ElMassimo/9ee7c89d0016879b127cb80c6dc9187d to your computer and use it in GitHub Desktop.
Save ElMassimo/9ee7c89d0016879b127cb80c6dc9187d to your computer and use it in GitHub Desktop.
How to configure resolve.alias by using paths in tsconfig.json
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