Vite is a great build tool for your frontend assets. It works nicely with popular frontend frameworks, like Vue.js. When looking for Vue.js tutorials on the Internet you may find code outlining Vue single file components. The imports in the tutorials may start with an @
symbol, like a starting point from the project‘s root directory.
This tutorial shows you how to create aliases in Vite which resolve to a given directory path.
Vite Series Overview
- How to Fix „Uncaught SyntaxError: Unexpected token 'export‘“
- Resolve `import.meta.glob` in TypeScript
- Create Resolve Aliases for Imports (Like the @ Symbol)
Create the @ Symbol Alias in Vite
This tutorial uses the @
symbol as an alias. It’s a common alias in Vue.js projects resolving the root path of your frontend code.
You need to define aliases in your vite.config.ts
file. If you’re using a JavaScript-based project, your Vite configuration file is named vite.config.js
. Inside your Vite config file, you need to provide the resolve.alias
option. This setting is passed to the @rollup/plugin-alias
package to resolve the defined paths.
The alias configuration can be an object or an array of objects exposing { find, replacement, customResolver }
attributes. Here's a sample Vite alias config for the @
symbol resolving the base of the frontend’s code inside of the ./src
directory:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath } from 'node:url'
/**
* @see https://vitejs.dev/config/
*/
export default defineConfig({
plugins: [
vue(),
],
resolve: {
alias: [
{
find: '@',
replacement: fileURLToPath(new URL('./src', import.meta.url))
},
]
}
})
IntelliSense for Vite Aliases With TypeScript
IntelliSense is great for your developer experience while writing code. We highly recommend configuring a path alias in your tsconfig.json
file to get proper IntelliSense in your editor or IDE.
Here’s how you define your @
symbol alias path mapping to tell TypeScript how to resolve imports starting with @/
:
{
"compilerOptions": {
"target": "ES2020",
// … all other compiler options
// all paths defined here must match the configured path in `vite.config.ts`
"paths": {
"@/*": [
"./src/*"
],
}
}
}
Make sure to use the same file paths between your Vite alias config and the TypeScript paths config.
Using Aliases in Vue.js
Your Vite aliases are now working. For example, you can use them in your Vue.js components to import any kind of value. Here’s a basic component importing a TypeScript type and a component using an alias:
<script setup lang="ts">
import { ref } from 'vue'
import type { User } from '@/shared/contracts'
import YourComponent from '@/shared/components/YourComponent.vue'
const user = ref<User>({ name: 'Future Studio' })
</script>
<template>
<YourComponent :user="user" />
</template>
That’s it.
Enjoy aliases in Vite and Vue.js!