Setup path aliases in React + Vite + TS Project 🤓

RMAG news

Out of the box, vite doesn’t provide an “@” path alias for src, but you can define your own aliases. I assume you are using the Vite preset for react-ts.

The steps to set this up:

Step 1:

install devDependencies @types/node // so that __dirname can be recognized

npm i D @types/node

in vite.config.ts:

// …
import * as path from path

export default defineConfig({
plugins: [react()],
resolve: {
alias: [{ find: @, replacement: path.resolve(__dirname, src) }],
},
})

This will inform Vite of his alias.

if you want to have many aliases you can make it like this:

// …
import * as path from path

export default defineConfig({
plugins: [react()],
resolve: {
alias: [
{ find: @, replacement: path.resolve(__dirname, ./src) },
{ find: @components, replacement: path.resolve(__dirname, ./src/components/) },
{ find: @assets, replacement: path.resolve(__dirname, ./src/assets) },
{ find: @data, replacement: path.resolve(__dirname, ./src/data) },
{ find: @pages, replacement: path.resolve(__dirname, ./src/pages) },
{ find: @public, replacement: path.resolve(__dirname, ./public/) },
],
},
})

or

// …
import * as path from path

export default defineConfig({
plugins: [react()],
resolve: {
alias: {
@: path.resolve(__dirname, ./src),
@components: path.resolve(__dirname, ./src/components/),
@assets: path.resolve(__dirname, ./src/assets),
@data: path.resolve(__dirname, ./src/data),
@pages: path.resolve(__dirname, ./src/pages),
@public: path.resolve(__dirname, ./public/),
},
},
})

for alias naming can be done freely, I added @ in front of the alias name just to indicate it is an alias, this is just my optional approach. this is all up to you.

Step 2:

We add the alias “@” to the src directory in tsconfig.json

tsconfig.json:

{
compilerOptions: {
// …

types: [node],
baseUrl: .,
paths: {
@/*: [./src/*, ./dist/*, “”],
@components/*: [src/components/*],
@assets/*: [src/assets/*],
@data/*: [src/data/*],
@pages/*: [src/pages/*],
@public/*: [public/*]
}
},
include: [src],
references: [{ path: ./tsconfig.node.json }]
}

Usage:

on the file you want to import an alias:

import Comp from @components/Comp..

// …

that’s all, hope it’s useful 🤓⭐😎😊

Leave a Reply

Your email address will not be published. Required fields are marked *