4

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?

shekhardtu
  • 4,335
  • 7
  • 27
  • 34

1 Answers1

10

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/*"]
}
shekhardtu
  • 4,335
  • 7
  • 27
  • 34
  • Okay, that initially solved my problem, but now when I import my component, the import looks like this: `import Container from '../Container'` but i wanted something like `import Container from '@components/Container'` – Jonas Tolentino Feb 20 '23 at 21:47
  • Your import should look like this "import Container from "Container", if this is not the case, there might be some configuration issue. – shekhardtu Feb 21 '23 at 09:00
  • it works for me in one dir and doesn't work in other dir. Damn, I don't know why – Fayaz May 28 '23 at 07:41