Issue with using @ symbol in src alias in vite/vue project causing malfunction

Recently, I set up a Vue3/TS project using the Vite CLI

The configuration in my vite.config.ts is as follows:

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

export default defineConfig({
    plugins: [vue()],

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

In addition, I included a 'paths' property inside tsconfig.json:

{
    "compilerOptions": {
        ...
        "baseUrl": "./",
        "paths": {
            "@/*": ["./src/*", "./dist/*"]
        }
    },
    "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

Using this setup, I encountered an issue with dynamic imports and template strings:

<script setup lang="ts">
import { useStore } from '@/store/app'
import { computed, defineAsyncComponent } from 'vue'

const store = useStore()
const userRole = store.getUserRole

const component = computed(() => {
    return defineAsyncComponent(
        () => import(`@/components/pages/dashboard/${userRole}.vue`)
    )
})
</script>

This code snippet resulted in an error:

Uncaught (in promise) TypeError: Failed to resolve module specifier '@/components/pages/dashboard/admin.vue' at dashboard.vue:14:54

When I replaced '@' with dot-notation, it worked perfectly. I need some assistance with this issue)

Answer №1

Here is an alternative approach:

solution: {
  alternate: {
    '@': path.resolve(__dirname, 'src'),
  }
}

Answer №2

Your defined alias looks good, but there is a slight detail missing when it comes to importing dynamic assets using Vite. I have already covered this in a previous response on Stack Overflow (link) (even though it was for Vue, the principles apply to Vite).

While the '@' alias works well for simple component imports, I encountered an issue with dynamic imports using template strings:

By replacing '@' with dot-notation, the problem was resolved. Would appreciate your assistance.

This limitation stems from Rollup restrictions. All imports should be relative to the importing file and cannot start with a variable.

To address this, you will need to swap out the alias (@/) with either a relative or absolute path like ./components or /src/components, as you have already implemented:

const component = computed(() => {
    return defineAsyncComponent(
        () => import(`./components/pages/dashboard/${userRole}.vue`)
    )
})

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

What could be causing the issue with my connection.query when using mysql in node.js?

Purpose: The goal is to perform a basic query on the database. Expected Outcome: The console should display "please print something!" along with the results of the query. Actual Outcome: Sadly, nothing appears on the terminal screen. Issues: No error me ...

Navigate between tabs with a single click

Hey there! I'm having trouble putting together a webpage that features a sidebar. I want to make it so that clicking on one of the links at the top will switch the tab and its content accordingly. However, the current code I have isn't working an ...

My current array is arr=[1,2,3,4]. I recently added an element to it using arr.push(5). Now I want to rearrange the array to be [5,4,3,2,1]. Any suggestions on how to achieve this

I currently have an array in the following format: var arr = [1,2,3,4] // Add another element to the array arr.push(5) // Now, arr = [1,2,3,4,5] I want to print my array as The elements in the array arr are: 5,1,2,3,4 When I use Arr.reverse(), it retu ...

What is the best way to convert a Nextjs page into a PDF file?

I am currently working on a page structure that looks like this: export default function FichaTecnica(props) { const data = props.data; return ( <> <Container> <TopData info={data} /> <DataSheet datasheet= ...

The difference between `$(document)` and `$("document")` is like night

Does a distinction exist between: $(document) and $("document")? ADJUSTMENT: also when using the .ready() method like $("document").ready() ...

What is the best way to create a mock URL in axios for unit testing purposes?

Scenario In this application, the URL is only accessible in production and cannot be accessed locally. During unit testing, it becomes necessary to mock the response from that URL. Solution Refer to this helpful tutorial for guidance. Current Implement ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

Unlocking the full potential of Vuejs with role-specific logins and varied

I am currently in the process of learning vue js and I have taken on a project that involves role-based login and generating report listings. The project design includes two types of users: HAuser and supplier. How can I implement a system to redirect each ...

Is there a way to incorporate additional text into option text without compromising the existing values?

One challenge I'm facing is adding additional text to the options without changing their values upon selection. Would you be able to assist me with resolving this issue? I have come across the following HTML code: <select id="q_c_0_a_0_name"> ...

Monitor the input value for any changes in Angular 8 using the listen component

Hey there! I'm currently working with a component that includes the input @Input() userId: number[] = []; to receive a list of user IDs. Specifically, I have integrated this component into another one, such as the news component: <kt-user-post-li ...

Incorporating lazy loading for diverse content to enhance pagination

I'm currently using jpaginate for pagination on a large dataset, but I've noticed that all the content loads at once. Is there a jQuery plugin available that will only load the content for the current page? ...

Leveraging Vue.js for implementing reusable form validation rules

It seems like I'm repeating a lot of code within my form components. Each form component follows this structure: template <v-col cols="12" sm="6" md="4"> <v-text-field name="name" v-model="user.name" ...

Incorporating timed hover effects in React applications

Take a look at the codesandbox example I'm currently working on implementing a modal that appears after a delay when hovering over a specific div. However, I've encountered some challenges. For instance, if the timeout is set to 1000ms and you h ...

Is there a way to set a default value for an Angular service provider?

Imagine an Angular Service that encapsulates the HTTP Client Module. export class HttpWrapperService { private apiKey: string; } Of course, it offers additional features that are not relevant here. Now I'm faced with the task of supplying HttpWr ...

No need for jQuery with this scrolling image gallery

I recently created a horizontal scrolling image gallery with thumbnails underneath. The goal is to click on a thumbnail and have the corresponding image scroll into view. Here's the HTML setup: <div class="images_container"> <img id="imag ...

Adding hidden elements with jQuery: A comprehensive guide

I need assistance with adding the "is-hidden" class at this specific spot <span class="tag is-danger is-rounded is-small is-bolded span_notif_count ... "></span> As a beginner in jQuery, I am unsure about how to proceed. Could someon ...

Vue.js - Issue with event not being fired upon clicking a button within a component

In my current setup, there is a specific component enclosed within a modal tag. Upon clicking this component, the modal window opens and fetches content from a designated URL. <modal> <laravel-view :url="'{{ '/post/view/' . $commen ...

Looking to obtain rendered tree data upon page load?

Is there a way to retrieve all rendered tree metadata when the page loads using jstree? I'm looking for an output similar to this: [23,24] Please note that I would like to have each id stored in the metadata object displayed as [23,24] upon page loa ...

How can I call a function from one Vue component in another component?

I have developed a component with the function "logout" as seen in the code snippet below: // @/component/Painel.vue <template></template> <script> export default { name: 'panel', methods: { logout: function () { ...

Vuejs Countdown Timer Powered by Moment.js

Currently, I am working on a vuejs page and I am looking to incorporate a countdown timer that counts down from 5 minutes (e.g. 5:00, 4:59, and so on). Although I have never used momentjs before, I have gone through the moment docs but I am finding it ch ...