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

The Angular service encounters issues when interacting with REST API

Within my application, a template is utilized: <div class="skills-filter-input" ng-class="{'hidden-xs': skillsFilterHidden}"> <input type="text" ng-model="skillQuery" ng-change="filterSkills()" placeholder="Filter skills" class="filter- ...

Is there a way to compel @keyframes to continue playing until it reaches its conclusion even after a mouseout event

Whenever I hover over an element, a keyframe animation starts playing. However, when I move the cursor away, the animation stops abruptly. Is there a way to ensure that it plays until the end? I've tried using the animationend event, but it doesn&apos ...

Encountered an error while running the `npx-create-react-app my-app` command in

When attempting to run 'npx create-react-app my-app', the following error message is displayed: 'npx' is not recognized as the name of a cmdlet, function, script file, or operable program. Double check the spelling and path included to ...

How can the callback from C++ be successfully installed in the Javaobject window within QtWebkit?

I have successfully implemented HTML-JS to call a C++ method using QtWebkit. Now, I want to send a callback from the C++ method to the JavaScript window. How can I achieve this? Below is my code snippet. #include <QtGui/QApplication> #include <Q ...

Tips for utilizing the <base> element in HTML5 for selective anchor tags

I only have one base tag in the head section of my HTML document, and there are two anchor tags with different URLs as shown below: <!DOCTYPE html> <html lang="en"> <head> <base href="https://www.youtube.com"/> </head> &l ...

The system encountered an issue: "Property 'add' is not defined and cannot be read."

I'm facing a dilemma with my exercise. Despite the numerous inquiries regarding this problem, I haven't been able to find a solution. I am hopeful that you can provide some assistance! Below is the code snippet in question: let myDivs = docume ...

What is the best way to efficiently load all of my web applications within the web application that I am currently developing?

https://i.stack.imgur.com/IAjIW.png Greetings! I am currently a novice Web Developer and here is my current situation: I am working on developing 3 web applications, with one additional application that will load all three of them. Please refer to the im ...

Gain access to the iterable within the adjacent tag

I am looking to access an iterable from a sibling tag, but unfortunately it is within a table which complicates things. Simply wrapping the content in a div and moving the iteration outside is not possible due to the structure of table rows. Here is an exa ...

What is the reason for npm and yarn to download multiple versions of jquery?

For the purpose of investigating how package managers like npm, yarn, and cnpm work in Node.js, I conducted an experiment. During the test, I came across two packages: jquery-dreamstream and jquery.tree. Both of them have a dependency solely on jquery wit ...

What is the method for retrieving post ID with the Google Feed API?

I am currently utilizing two different JS codes to dynamically load posts from my Wordpress website: Code 1: JSON API <script src="http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=listPosts" type="text/javascript">& ...

Issue with styled-components not being exported

Issue: ./src/card.js There was an import error: 'Bottom' is not exported from './styles/cards.style'. card.js import React from 'react' import { Bottom, Color, Text, Image } from "./styles/cards.style"; fu ...

How can I reset a CSS position sticky element using JavaScript?

I have created a page where each section fills the entire screen and is styled using CSS position: sticky; to create a cool layered effect. Check it out here: https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark ...

I Tried Adding Up All the Numbers, but It Doesn't Seem to Work for Every Dynamic Total Field

In my project, I am utilizing Laravel 5.7 and VueJs 2.5.*. The issue I am facing is that when I input values, the Total field calculates correctly. However, when I dynamically add rows for items, the calculation only works for the first row and not for the ...

The submit button fails to produce any result

I have a submit button in a contact form that triggers PHP code to send an email. However, when I press the button nothing happens - not even the PHP code is displayed as it should be if PHP were not installed. Interestingly, I have tested other simple mai ...

Adding a command to open a new browser tab using JavaScript code can easily be accomplished by following these steps. By using Terminal, you can quickly and efficiently implement this feature

I'm new to coding and trying to create a terminal simulation. You can check out my code here: https://codepen.io/isdampe/pen/YpgOYr. Command: var coreCmds = { "clear": clear }; Answer (to clear the screen): function clear(argv, argc ...

Transmitting various pieces of information using AJAX

Is it possible to send both "credit_uri" and "address" strings in one AJAX request? Currently, only the second string is being sent. How can I include both in the data of the request? $.ajax({ url: '#{add_cards_path}', type: 'POST&apo ...

The function canvas.toDataURL() is not recognized - error originating from a node-webGL wrapper

I am currently working on converting client-side volume rendering code in the browser to server-side rendering using pure JavaScript. On the server side, I am utilizing node-webgl. My objective is to send the server's canvas content to the client so ...

"The website seems to be experiencing some technical difficulties on Firefox, but I have switched to

I attempted to reset the text area after sending a message with the code below: $(document).keypress(function (e) { if (e.which == 13) { e.preventDefault(); var $form = $('#f1'); $.ajax({ url: $form.attr( ...

How come the express.static() function is failing to load my .js and .css files from the intended path?

const express = require('express'); const app = express(); const server = require('http').Server(app); const io = require('socket.io').listen(server); const path = require('path'); let lobbies = new Array(); app.us ...

You won't be able to view over 15 KML layers on a page that relies on Google Maps API

I've encountered an unusual issue: I need to create multiple KML layers from separate KML files and display them on a single map window. The number of files ranges from just a couple to less than fifty. Currently, my code works perfectly when given 1, ...