Search code examples
javascripttypescriptvue.jsvitevitest

How can I solve the issue of 'failed to resolve import in '@/...'" vitest?


This is the error I got. There is a problem with the file path I defined in the "vite.config.ts" file. Can you help me?

Error Log

Error Message:

FAIL  tests/utils/ConvertFromDomainToCountryCode.test.ts [ tests/utils/ConvertFromDomainToCountryCode.test.ts ]
Error: Failed to resolve import "@/constant" from "src/assets/ts/_utils/ConvertFromDomainToCountryCode.ts". Does the file exist?

ConvertFromDomainToCountryCode.test.ts file

import { describe, expect } from "vitest";
import { SetFlags } from "../../src/assets/ts/_utils/ConvertFromDomainToCountryCode.ts";

describe("Convert From Domain To CountryCode", () => {
  test("function defined", () => {
    expect(SetFlags).toBeDefined();
  });
});

Here it works fine when I make the file path "../../../constant/index".

ConvertFromDomainToCountryCode.ts file

import { COUNTRY_INFO } from "@/constant";

Here i added "alias"

vite.config.ts file

import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve, dirname } from "node:path";
import vueJsx from "@vitejs/plugin-vue-jsx";

export default defineConfig({
  plugins: [
    vue(),
    vueJsx()
  ],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url))
    }
  },
  base: "/"
});

System

OS: macOS 13.2.1
CPU: (8) arm64 Apple M1 Pro
Memory: 91.50 MB / 16.00 GB
Shell: 5.8.1 - /bin/zsh
Binaries:
Node: 16.18.1 - ~/.nvm/versions/node/v16.18.1/bin/node
Yarn: 1.22.19 - ~/.nvm/versions/node/v16.18.1/bin/yarn
npm: 8.19.2 - ~/.nvm/versions/node/v16.18.1/bin/npm
Browsers:
Chrome: 111.0.5563.64
Safari: 16.3
npmPackages:
@vitejs/plugin-vue: ^3.1.2 => 3.2.0
@vitejs/plugin-vue-jsx: ^3.0.0 => 3.0.0
@vitest/coverage-istanbul: ^0.29.3 => 0.29.3
vite: ^3.1.8 => 3.2.5
vitest: ^0.29.3 => 0.29.3

Just waiting for the path of the file to be found


Solution

  • I solve this error. I add this code in vitest.config.ts file.

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