If you’re using Vite in a monorepo or any project setup with aliased imports, you may have encountered the following error:

vite] Pre-transform error: Failed to resolve import

The Cause:

This issue happens because Vite uses absolute paths when resolving modules, but it mistakenly treats paths like "src/*" as a package in node_modules. This leads to import resolution problems, especially when using custom path aliases in your project.

The Solution:

To fix this, you need to update your tsconfig.json to correctly define how paths should be resolved.

Step-by-Step Guide

1. Update Your tsconfig.json

Modify your tsconfig.json file by specifying how Vite should handle module imports. Here’s an example of the configuration:

// tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@src/*": ["src/*"]

}
}
}

The key change is to ensure that you prefix all your paths with a /. This tells Vite that these are not packages but rather project-relative paths.

2. Update vite.config.ts

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  // Resolve path aliases
  resolve: {
    alias: {
      '@src': '/src'
    }
  },
}

2. Modify Your Imports

Now that you’ve updated tsconfig.json, you can import modules using absolute paths. For example, in your App.tsx file:

// App.tsx
import { Home } from "@src/pages/Home";

3. [Optional] Monorepo Setup Paths with Alias

If you’re using a monorepo setup with multiple packages, you can extend the paths configuration to accommodate different packages:

// tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"/@src/*": ["src/*"],
}
}
}

This setup ensures that Vite can resolve modules from different parts of your project while using absolute paths.

Conclusion

By prefixing your paths with a / and configuring tsconfig.json properly, you can resolve Vite’s import issues. This method makes path aliases work seamlessly and eliminates the “Failed to resolve import” error.

Feel free to apply this fix to other paths based on your project structure!