Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute imports: React + TypeScript + Vite

Issue

I have an react app built by yarn create vite

I wanted to use absolute imports instead of "../../.." in my files, but it doesn't work in my React + Vite app. And everything works fine in IDE. It defines my imports and redirects to my files.

Here is my import in the file.

import HomePage from '@/pages/HomePage/HomePage.tsx';

But I've got an error directly at compilation time.

[plugin:vite:import-analysis] Failed to resolve import "@/pages/HomePage/HomePage.tsx" from "src\routes\Routes.tsx". Does the file exist?

What I tried

I configured my tsconfig.json and specified "baseUrl", "paths" and "include" fields.

tsconfig.json:

{
  "ts-node": {
    "files": true
  },
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "dist",
    "declaration": true,
    "strictNullChecks": true,
    "sourceMap": true,
    "strict": true,
    "skipLibCheck": true,
    "jsx": "react",
    "declarationDir": "types",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "allowImportingTsExtensions": true,
    "emitDeclarationOnly": true,
    "baseUrl": "src",
    "paths": {
      "@/*": [
        "*"
      ]
    }
  },
  "include": [
    "src"
  ],
  "references": [{ "path": "./tsconfig.node.json"}]
}

vite.config.ts:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import reactRefresh from '@vitejs/plugin-react-refresh'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), reactRefresh()],
  resolve: {
    alias: {
      '/@': path.resolve(__dirname, 'src'),
    },
  },
  css: {
    modules: {
      localsConvention: 'camelCaseOnly',
    },
  },
})

In WebStorm -> Preferences -> Editor -> Code Style -> JavaScript -> Imports I checked Use paths relative to the project, resource or source roots.

Meanwhile ESLint and WebStorm give no errors.

like image 621
Mikhail Ganin Avatar asked Dec 20 '25 14:12

Mikhail Ganin


1 Answers

The problem was in vite.config.ts. I removed an extra '/' from the path and it's started working properly. From:

alias: {
  '/@': path.resolve(__dirname, 'src'),
},

To:

alias: {
  '@': path.resolve(__dirname, 'src'),
},
like image 125
Mikhail Ganin Avatar answered Dec 23 '25 10:12

Mikhail Ganin