How to configure path aliases w/Vite + Vue/React

Joshua OmobolaJoshua Omobola
2 min read

While building Humanizer, I hit a snag while trying to import a component using the '@' path alias to src.

What you get if path aliases aren't configured in your project

That's when I realised that Vite does not provide path aliases(@/~) out of the box. If we want to use that, we would need to set it up ourselves.

Hi, I am koha and In this short article, I will show you how to configure your Vite Project, vue or react, to work without fuss with path aliases.

Why Path aliases

Path aliases clean up your import statements. And beyond that, it contributes greatly to having a maintainable codebase. Get rid of those ../.../.../ sort of imports today and use path aliases. Just do it. โ˜˜๏ธ

Configuring Path Aliases

In your vite.config.js file, at the top of the file, import the path module.

import * as path from 'path';

Then add the resolve option to the object passed to defineConfig:

export default defineConfig({
  // ... rest of the code
  resolve: {
    alias: [{ find: "@", replacement: path.resolve(__dirname, "src") }],
  },
});

That would inform vite of the alias and now '@' should now resolve correctly to /src/.

Your vite.config.js file should look like this now. Yours might be slightly different if you have other things set up

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import * as path from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [{ find: "@", replacement: path.resolve(__dirname, "src") }],
  },
});

Using path alias

Now you can reference components, imports or whatever really using a @.

import TheHero from "@/components/TheHero.vue";

Everything should work fine if you followed the guide correctly.

Awesome! ๐Ÿš€ You Just configured your project to use path aliases and supercharge your workflow.

I hope this article has been useful. If you want snappy, super fast content like this, you can follow me here and in one click you would be notified of my next post.

Do leave a comment if you've got any questions and contributions.

Koha.

5
Subscribe to my newsletter

Read articles from Joshua Omobola directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Joshua Omobola
Joshua Omobola

Developer Relations Engineer. Blockchain Engineer. Designer. Aesthete. Curious. Creator. Lover of Cyborgs. Figma overlord. Solarpunk. Vue Enforcer. Open Source has my soul.