How To Create An Alias For A Vite Project

Creating alias to use for your code makes larger projects with deeply nested files much more readable and easier to navigate.

We’ve found, especially in the cases of writing tests, sometimes you end up with something like:

import { Component } from ../../../src/components/Component.vue

This is doesn’t look very nice at all, and become pretty unmanagable as the project grows. So, let’s add an alias!

In your vite.config.js, there is an option on the object to add in a ‘resolve’ property to it.

resolve: {
		alias: [{ find: "@", replacement: path.resolve(__dirname, "src") }],
	}

All you need to do, is make sure that path is imported and you’re good to go!

An example config would look like so:

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

export default defineConfig({
	plugins: [vue()],
	test: {
		globals: true,
		environment: "jsdom",
		setupFiles: ["./src/tests/setup.js"],
	},
	resolve: {
		alias: [{ find: "@", replacement: path.resolve(__dirname, "src") }],
	},
});

The best thing about doing this in the Vite config, if you’re using something like Vitest (which is a testing framework from the creators of vite), your aliases will just work in your test files!

This is an instance productivity booster.

Happy coding!

Sponsored by Vizalo

Protypo is sponsored by Vizalo - powerful yet affordable servers with locations in Europe and North America.