Published on

How to Fix 'Failed to Resolve Import in '@/...' in Vitest

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Fix 'Failed to Resolve Import in '@/...' in Vitest

Understanding the Issue

When working with Vitest in a Vite project, you might encounter this error:

Error: Failed to resolve import "@/constant" from "src/assets/ts/_utils/ConvertFromDomainToCountryCode.ts". Does the file exist?

This issue arises when path aliases like @ are not correctly configured for Vitest, even though they work perfectly in your Vite project.


Root Cause

The vite.config.ts file correctly defines aliases for your Vite project. However, Vitest requires separate alias configuration in its own configuration file (vitest.config.ts or vite.config.ts if shared). Without this, Vitest cannot resolve the aliases, resulting in the error.


Solutions

1. Configure Aliases in Vitest

To resolve this issue, update your vitest.config.ts to include the alias configuration.

Step-by-Step Guide:

  1. Import the required modules in vitest.config.ts:
import { defineConfig } from 'vitest/config'
import { resolve } from 'path'
  1. Add the resolve.alias field with the correct alias setup:
export default defineConfig({
  resolve: {
    alias: [{ find: '@', replacement: resolve(__dirname, './src') }],
  },
})

Now Vitest can resolve the @ alias to the src directory.

2. Use vite-tsconfig-paths Plugin

If your aliases are already defined in tsconfig.json, you can use the vite-tsconfig-paths plugin to automatically apply them.

Step-by-Step Guide:

  1. Install the plugin:
npm install vite-tsconfig-paths --save-dev
  1. Update your vitest.config.ts file to include the plugin:
import { defineConfig } from 'vitest/config'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  plugins: [tsconfigPaths()],
})

This ensures that Vitest reads aliases directly from your tsconfig.json.

3. Ensure Consistent Alias Keys

In frameworks like Nuxt.js or SvelteKit, you might need to use sass or other keys instead of scss. For example:

resolve: {
  alias: [
    { find: "@components", replacement: resolve(__dirname, "./src/components") },
  ],
}

Common Pitfalls

  • Missing resolve Import: Ensure you import resolve from path:
    import { resolve } from 'path'
    
  • Incorrect Alias Path: Double-check the alias path matches your project structure. For instance, "./src" must point to the correct root folder.
  • Plugins Overlapping: Avoid duplicate alias configurations if you use vite-tsconfig-paths.

Example vitest.config.ts

Here’s the full example of a working configuration:

import { defineConfig } from 'vitest/config'
import { resolve } from 'path'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  plugins: [tsconfigPaths()],
  resolve: {
    alias: [{ find: '@', replacement: resolve(__dirname, './src') }],
  },
})