Vue - The Road To
        Enterprise logo
The Most Advanced Vue Book Buy Now

How to set up path resolving in Vite

undefined article image

Some time ago I have tried to use Vite for some of my tutorial projects. After setting up a project with Vite and creating a new component, I tried to import it the usual way I would do it when working with projects scaffolded with Vue-CLI, with the @ sign that resolves to the src directory. To my surprise, it did not work and I was welcome with this error:

Failed to resolve import error

It turns out that Vite does not have src path resolving by default. Fortunately, it's quite easy to configure it.

Path aliases

We can configure Vite by modifying the vite.config.js file. We need to tell Vite how it should resolve the paths by providing resolve.alias config. Here is the code for resolving the @ sign to the src directory.

vite.config.js

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

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
})

There is one more thing we need to do. It's a good idea to tell your code editor how it should resolve your aliases. You can do so by creating a jsconfig.json, or ts.config.json file if you're using TypeScript.

jsconfig.json

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

Without setting it up, if you would try to import a component like import CMP from "@/component/...path", there would be no intellisense for it.

I hope you found this article useful. If you would like to learn more tips, advanced patterns, techniques and best practices related to Vue, you might want to check out "Vue - The Road To Enterprise" book, sign up for the newsletter, and follow me on Twitter.


Want to learn something new?

Subscribe to the newsletter!


Thomas Findlay photo

About author

Thomas Findlay is a 5 star rated mentor, full-stack developer, consultant, technical writer and the author of "The Road To Enterprise" books. He works with many different technologies such as JavaScript, Vue, Nuxt, React, Next, React Native, Node.js, Python, PHP, and more. He has obtained MSc in Advanced Computer Science degree with Distinction at Exeter University, as well as First-Class BSc in Web Design & Development at Northumbria University.

Over the years, Thomas has worked with many developers and teams from beginners to advanced and helped them build and scale their applications and products. He also mentored a lot of developers and students, and helped them progress in their careers.

To get to know more about Thomas you can check out his Codementor and Twitter profiles.