This article was originally published at The Road To Enterprise.
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:
It turns out that Vite does not have src path resolving by default. Fortunately, it's quite easy to configure it.
Learn industry-level skills with the most advanced React book available.
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.
Conclusion
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.