This content originally appeared on DEV Community 👩💻👨💻 and was authored by Joshua Omobola
While building Humanizer, I hit a snag while trying to import a component using the '@' path alias to src.
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.
Conclusion
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.
This content originally appeared on DEV Community 👩💻👨💻 and was authored by Joshua Omobola
Joshua Omobola | Sciencx (2022-09-05T23:59:30+00:00) How to configure path aliases w/Vite + Vue/React. Retrieved from https://www.scien.cx/2022/09/05/how-to-configure-path-aliases-w-vite-vue-react/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.