DEV Community

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

Posted on • Updated 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 project, create a jsconfig.json or tsconfig.json 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/components/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)