I’m using Vite with React, and I want to use path aliases to make my imports shorter and more manageable. I have configured the alias in the vite.config.js file, but I am getting the error:
[vite] Internal server error: Failed to resolve import “api/auth” from “src/pages/Auth/Step1.jsx”. Does the file exist?
Your vite.config.js should now look like this:
import path from "path";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
Configuring VS Code IntelliSense:
To configure VS Code intelliSense, you simply need to create a new file named jsconfig.json in the root directory of your project and add the following code to the file:
{
"compilerOptions": {
"paths": {
"@/*": [
"./src/*"
]
}
}
}
Now that path aliases are set up, you can start using them in your code. For example, instead of writing:
import Button from "../../../components/Button"
You can now use path aliases:
import Button from "@/components/Button"
In this guide, we’ve explored the power of path aliases in React Vite projects. By setting up path aliases, you can enhance code readability, simplify maintenance, and make your development workflow more efficient. With these techniques, you’ll be well on your way to creating more maintainable and scalable React applications.
Happy coding 😉