Vite Absolute Path

Recently I've been developing my React projects with Vite instead of CRA. It is both faster and we can use the staging event in the build process without any additional settings, which is an advantage. With absolute path in CRA and Vite, the setups are slightly different.

With Absolute Path, we can define a precise path and call our files using this precise path definition wherever we are. So import operations like this:

import Header from '../../components/Header'
import HeroSection from '../../components/HeroSection';
import { numberFormat } from '../../../helpers/Mixins';

Ultimately to use like this:

import Header from '~/components/Header'
import HeroSection from '~/components/HeroSection';
import { numberFormat } from '~/helpers/Mixins';

Follow these steps:

If you're using typescript, create tsconfig.json if you're using javascript, create the jsconfig.json file in your home directory and write the following in it:

{
	"compilerOptions": {
	    "baseUrl": "./src",
	    "paths": {
	      "~/*": ["./*"]
	    }
	}
}

and open your vite.config.(ts|js) file and add:

resolve: {
    alias: {
      '~': path.resolve(__dirname, 'src'),
    },
  },

If path can't find it, import it like this at the top:

import * as path from "path"

Restart Vite and you're ready :)

Comments

There are no comments, make the firs comment