What strategies can I use to address the problem of 'unable to resolve import in '@/...'" in vitest?

I encountered an error related to a file path defined in the "vite.config.ts" file. Can you assist me with this issue?

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();
  });
});

It works fine when I use the file path "../../../constant/index".

ConvertFromDomainToCountryCode.ts
file

import { COUNTRY_INFO } from "@/constant";

I have added an "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

Currently waiting for the file path to be located.

Answer №1

After some troubleshooting, I successfully resolved this issue by including the following code snippet in the vitest.config.ts file:

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

Answer №2

Encountered a similar issue and found a solution that worked, but wanted to share an additional tip. You can also include the import resolve statement from the path module:

import { resolve } from 'path'

If you have not defined the "@" symbol in your tsconfig file but need to specify dynamic paths for certain folders, you can do so by including the following configuration:

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

Answer №3

I found success with the utilization of vite-tsconfig-paths. This method allows for the automatic reading of aliases set in tsconfig.json within the vitest.config.ts file.

  1. Begin by executing

    npm install vite-tsconfig-paths --save-dev

  2. Make adjustments to vitest.config.ts:

    import { defineConfig } from 'vitest/config';
    import { defineConfig as viteDefineConfig } from 'vite';
    import tsconfigPaths from 'vite-tsconfig-paths';
    
    export default defineConfig(
      viteDefineConfig({
        // ... other Vite configurations
        plugins: [tsconfigPaths()],
      }),
    );
    

Answer №4

While working on my code that utilized Material UI icons (v5), I ran into an issue with the default import of material icons provided by Material UI 4. The import statement I initially used was:

import CheckCircleIcon from '@mui/icons-material/CheckCircle';

The error message I encountered was:

[plugin:vite:import-analysis] Failed to resolve import "@mui/icons-material/CheckCircle" from "src/auth/components/Pricing/PricingTable.tsx". Does the file exist?

Since my code was based on Material UI version 4, I had to adjust the import statement to:

import CheckCircleIcon from "@material-ui/icons/CheckCircle";

After making this update, the issue was resolved, and the component functioned as intended.

Answer №5

After trying multiple solutions without success, I finally found the one that resolved my issue:

import { defineConfig } from 'vite';
import path from "node:path";

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic Vue/Vuex component remains stagnant

In my Vuex store, I have a collection of "nodes" where each node is categorized as either an Accordion or a Block. { "1":{ "id":1, "title":"Default title", "nodes":[], "type":"Block" }, "2":{ "id":2, "title":"Default title", ...

React-Bootstrap columns are not displaying in a side by side manner and are instead appearing on separate lines

I am currently integrating Bootstrap into my React project alongside Material UI components. Below is a sample of one of my components: import { styled } from "@mui/material/styles"; import Paper from "@mui/material/Paper"; import Cont ...

Enhancing fullcalendar with Vue Js: A step-by-step guide

Issue: I am facing a challenge in customizing my Full calendar view. Objective: My goal is to set the default view to month. While I have achieved this using JQuery, I am curious about how to accomplish the same with Vue-js. My Investigation: My JQuer ...

"Enhance Your Website with jQuery: Organized Lists with Fixed Length, Connected,

I currently have a list that is separated into three columns, structured as follows: Column1 Column2 Column3 1 4 7 2 5 8 3 6 9 The list ranges from 1 to 9 and each column consists of a fixed number of rows (3). I am lo ...

Why do I keep encountering the error "global is not defined" when using Angular with amazon-cognito-identity-js?

To start, run these commands in the command line: ng new sandbox cd .\sandbox\ ng serve Now, navigate to http://localhost:4200/. The application should be up and running. npm install --save amazon-cognito-identity-js In the file \src&bso ...

What is the best way to establish communication between a server and client using sockets in Node.js?

Presently, I am in the process of developing a JavaScript application using AppJS. I'm encountering some difficulties understanding the communication between the client and server. Issue with Menu Bar and Socket Interaction The main challenge lies ...

Is it possible to modify the inline onkeyup function?

Looking for a solution to change the onkeyup function in a textarea element from 255 characters to 150 characters without directly editing the code? <textarea cols="50" rows="4" id="textbox" onkeyup="limitArea(this, 255, '')"></textarea ...

An Error with jQuery Autocomplete: "Callback is not Defined"

I am currently working on a jQuery script that involves autocomplete and selecting the correct value on the client side. Here is my functional code without the selected value (it displays all username available in my JSON): $(function() { $( "#us ...

Prevent the element attribute from being enabled before the onclick function is triggered

I am attempting to implement a feature in Angular that prevents double clicking on buttons using directives. Below is the pertinent code snippet from my template: <button (click)="onClickFunction()" appPreventDoubleClick>Add</button> And her ...

Verify the accuracy of quiz responses with PHP and AJAX

I am working on a picture quiz that has one input field for each image. I am looking for a solution to verify if the value entered into the input field matches the correct answer. If it does match, I need to perform certain operations like adding or removi ...

What methods can be used to differentiate between value equality and reference equality when watching something?

In the world of AngularJS, the $watch function comes with an interesting twist - it has an optional third parameter. By default, this parameter is set to false, which means the watch will only trigger if the watched reference changes. But if you set it to ...

The DataTable bootstrap is throwing an error when trying to access the property aDataSort

I am currently learning about bootstrap and working on a project that involves displaying data in a DataTable. However, I encountered an error that says Cannot read property aDataSort of undefined Feel free to make edits to my code if there are any mistak ...

In TypeScript/Angular, what is the best way to share model variables between a Service class and a controller class?

Is there a way for the Controller and Service classes to access the same model without explicitly passing it? For example: Controller Class : import { SearchModel } from "../../models/SearchModel"; import { SearchService } from "../../components/SearchS ...

Set every attribute inside a Typescript interface as non-mandatory

I have defined an interface within my software: interface Asset { id: string; internal_id: string; usage: number; } This interface is a component of another interface named Post: interface Post { asset: Asset; } In addition, there is an interfa ...

How do I determine whether an object is a Map Iterator using JavaScript?

I'm working on some NodeJS code that involves a Map Iterator object. How can I accurately determine if a Javascript object is a "Map Iterator"? Here are the methods I have attempted: typeof myMap.keys() returns 'Object' typeof myMap.keys() ...

Check the length of a ngRepeat array after the initial filtering before applying limitTo for further refinement

Currently, I am implementing pagination in my Angular application by using a custom startAtIndex filter along with the limitTo filter. My goal is to show the total number of results in the dataset, regardless of the current page. However, due to the use of ...

Maintaining User Login State Across Route Changes in Vue with Vuex

Our small Dev-Team is excited to venture into creating our own social media website just for fun. We have implemented a login process using a jwt that is stored in localStorage. async login( { commit }, user) { commit('auth_request'); ...

Issue with Vue Composition API: Unable to append a property to an object

Currently, I am utilizing Vue's Composition API in my project. However, I have encountered an issue where the template renderer does not recognize changes when I add a property to a ref object. Below is the code snippet that demonstrates this problem: ...

The .keypress() function isn't behaving as expected

I've encountered a coding dilemma. Below is the code in question: $(document).ready(function () { var selectedDay = '#selected_day'; $(function () { $("#date").datepicker({ dateFormat: "DD, d M yy", a ...

What is the method for accessing the locale and messages of the IntlProvider within a component?

My index.js file includes the following code: import trFi from './translations/fi_FI.json'; import trSv from './translations/sv_SE.json'; ReactDOM.render( <IntlProvider locale={my_locale} messages={{ fi: trFi, sv: trSv } ...