DEV Community

Cover image for Spoiler Alert: Import Alias in React + Vite
Navdeep Mishra
Navdeep Mishra

Posted on • Edited on

Spoiler Alert: Import Alias in React + Vite

Today in this short article let's quickly learn how to set up path aliases in your React application. Avoid boring long imports in your app and start using path aliases now.

Pre-requisites
Must have a React app with vite. If you are still using CRA, checkout my guide to migrate your app to vite.

For Javascript Projects

  1. Update your vite config You have to update your vite config to make your aliases work.

Paste the following contents -



import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";

export default defineConfig({
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
      "@components": path.resolve(__dirname, "./src/components"),
      "@pages": path.resolve(__dirname, "./src/pages"),
      "@forms": path.resolve(__dirname, "./src/forms"),
      "@utils": path.resolve(__dirname, "./src/utils"),
      "@providers": path.resolve(__dirname, "./src/providers"),
      "@assets": path.resolve(__dirname, "./src/assets"),
    },
  },
  plugins: [react())],
});



Enter fullscreen mode Exit fullscreen mode

You can add your own folder according to your need. Likes hooks,context and etc.

  1. For Javascript/Typescript project, create a jsconfig.json or tsconfig.json (For Typescript Project) file in the root of your project. This step is necessary to make sure vs code intellisense works properly.

Paste the following contents -



{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
      "@components/*": ["./src/components/*"],
      "@pages/*": ["./src/pages/*"],
      "@assets/*": ["src/assets/*"],
      "@forms/*": ["src/forms/*"],
      "@providers/*": ["src/providers/*"],
      "@utils/*": ["src/utils/*"]
    }
  }
}



Enter fullscreen mode Exit fullscreen mode

This file will help your code editor intellisense to recommend you the path aliases during import.

That's all, now you can import a component like



import MyComponent from "@components/MyComponent";



Enter fullscreen mode Exit fullscreen mode

Thank you for reading this article. πŸ’“
Please share and follow for more dev content. πŸ˜„

Top comments (0)