DEV Community

Tarik Čaplja
Tarik Čaplja

Posted on

Absolute Imports: Vite TypeScript 2022

Hello. Everyone, I was trying to configure absolute import with Vite and TypeScript and I lost one day trying to configure it. I tried every Stackoverflow solution but non of them worked. So I decided to share with everyone this simple solution.

Step 1 - vite.config.ts

To configure absolute imports in vite we need to edit config file. Here is config file.

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

export default defineConfig({
  plugins: [react()],
  build: {
    // Here you define your build directory
    outDir: "./server/dist/",
  },
  // Here is config for absolute imports
  resolve: {
    alias: {
      // You can configure this in any way you like it
      // Below is my example
      "@components": "./src/components/",
      "@hooks": "./src/hooks/",
      "@utils": "./src/utils/",
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Step 2 - tsconfig.json

This is tricky part, not because it is hard to configure, but because it is very import to have * (wildcard) after defined path.

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    // To configure import you need to add paths config
    "paths": {
      // ⭐️ It is very important to put /* in both key and value config
      "@components/*": ["./src/components/*"],
      "@utils/*": ["./src/utils/*"],
      "@hooks/*": ["./src/hooks/*"]
    }
  },
  "include": ["src"],
}
Enter fullscreen mode Exit fullscreen mode

Valid config

"paths": {
      "@components/*": ["./src/components/*"],
      "@utils/*": ["./src/utils/*"],
      "@hooks/*": ["./src/hooks/*"]
    }
Enter fullscreen mode Exit fullscreen mode

Invalid config

"paths": {
      "@components": ["./src/components"],
      "@utils": ["./src/utils"],
      "@hooks": ["./src/hooks"]
    }
Enter fullscreen mode Exit fullscreen mode

Still have problem?

If you use VS Code try to restart TS server by pressing CMD+SHIFT+P and type TypeScript Restart TS Server.

Top comments (0)