How to set multiple aliases in vite react?

16.8k views Asked by At

Vite by default does not support src alias like

import counterReducer from "@src/pages/counter/counter.slice";

Every time you will have to pass the full relative path like this

import counterReducer from "../../src/pages/counter/counter.slice";

Is there any way we can shorten these relative paths?

1

There are 1 answers

4
shekhardtu On BEST ANSWER

Yes, vite doesn't come with the default configuration of aliases, but you can define your own aliases.

Step: 1 Open "vite.config.js" and add your aliases. vite.config.js

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src/"),
      components: `${path.resolve(__dirname, "./src/components/")}`,
      public: `${path.resolve(__dirname, "./public/")}`,
      pages: path.resolve(__dirname, "./src/pages"),
      types: `${path.resolve(__dirname, "./src/@types")}`,
    },
  },
});

Step 2: Open tsconfig.json or jsconfig.json and append this code under compiler options. tsconfig.json

"baseUrl": ".",
"paths": {
  "@/*": ["./src/*", "./dist/*", ""],
  "pages/*": ["src/pages/*"],
  "components/*": ["src/components/*"],
  "types/*": ["src/@types/*"],
  "public/*": ["public/*"]
}