Is there a way to retrieve the file path of the file that is imported using an alias in Vite (Vue3)?

Hello!

I have a few inquiries. Is it feasible to obtain the file path of the file utilizing an alias for import in Vite (Vue3)?

Setup

Here's the directory structure I'm using, purely for illustrative purposes:

src/ 
    module_a/ 
        some_script.js 
        another_script.js 
    module_b/ 
        some_script.js 
        another_script.js 
vite.config.js 

Situations

For instance, if I am in this particular file:

When importing as follows: src/module_a/some_script.js

import "#/another_script.js" 

...then, the # alias should automatically refer to ./src/module_a

Suppose when I'm in another module location ./src/module_b/some_script.js.

The code snippet reads:

import '#/another_script.js' 

...it should import ./src/module_b/another_script.js accordingly.

Main Inquiry

Can this be achieved within the vite.config.js file?

vite.config.js

    ...
    export default defineConfig({
        plugins: [vue()],
        resolve: {
            alias: {
            '@': path.resolve(__dirname, './src'),
            '#': (...args) => {
                console.log(args);    // outputs [#, 0, '@/path/of/script/to/import']
                
                // how to get this information below??? =(
                const filepathOfImportingScript = 
                    getImportingFilepath()  // <--- should return ./src/module_a/some_script.js
                
                const pathOfModule = 
                    getPathOfModule(filepathOfImportingScript);  // returns ./src/module_a/

                return path.resolve(__dirname, pathOfModule);
            }
        }
    })

My primary challenges include...

  • How do I implement the getImportingFilepath() function above which retrieves the filepath of the script utilizing the alias # for import?

  • Developing the getPathOfModule() function is more straightforward. However, implementing getImportingFilepath() poses a challenge.

I hope someone can provide insights, thank you!

Answer №1

After much searching, I have discovered the solution. I reached out to the Vite repository and a helpful individual provided me with the answer. Here is the link for anyone who may need it.

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

JavaScript's addition function is not functioning properly

Does anyone know how to calculate the sum of these variables? var totalPrice = document.values.T1.value; var pounds = document.values.T2.value; var serviceFee = 5.00 var counter1 = 0; var counter2 = 0; var processing = 0; var shippingCost = 0; var ...

Retrieve an array field across various documents and combine the elements to form a single object

Consider a scenario where there is a users collection. Each user document includes an array of posts called posts. The goal is to query this collection as follows: Retrieve 2 posts, starting at index Nstart and ending at index Nend, from each user in the ...

Unable to display the entire map within a DIV using VueJs and leaflet unless the screen is resized

I am using VueJS along with Leaflet to display a map with specific localization. I followed the instructions in the documentation by adding the Leaflet CSS link on index.html: @example/dist/leaflet.css"> However, I am only able to see a portion of t ...

Retaining the Chosen Tab upon Page Reload in Bootstrap 5.1

Struggling to maintain the selected tab active after page refresh. It's worth noting that I'm using Bootstrap 5.1 and have tried various solutions found for different versions without success. <ul class="nav nav-pills mb-3" id=&q ...

Flipping a combination of CSS 3 and JavaScript cards will cause them to flip all together in unison

Hello! I came across a really cool card flip code that is IE compatible. I made some modifications to it and got it working, but there's one problem - instead of flipping the selected card, it flips all the cards. I tried modifying the JavaScript code ...

The hyperlinks in the navigation bar are leading me to incorrect destinations

I am currently developing an authentication app and facing an issue with the navbar links for register and login. They are not redirecting me to the correct destination. These links work perfectly on the landing index page, but not on any other page. site ...

Parsing the JSON string from PHP using JSON.parse resulted in an unexpected and strange array

I've encountered a challenge when trying to transfer a JSON object from the server to client-side JavaScript. I fetched rows of data from a MySQL query and stored them in $result. Below is the code snippet: var json = '<?= json_encode($resu ...

Fancybox fails to acknowledge the thumbs feature

I received a sneak peek of five thumbnails for a gallery, but the actual gallery contains even more photos. To prevent cluttering my code, I decided to store them in an array. Here is the snippet of HTML code: <div id="start_slides"> <a href ...

Troubleshooting problems with anchor-targets in Skrollr

I am experimenting with having divs overlap each other as the page is scrolled using Skrollr. Initially, I was able to achieve the desired effect with two divs. However, when trying to incorporate a third div, only the first and last ones seem to work prop ...

Attempting to retrieve data from a JSON file according to the choice made by the user in a dropdown menu

My goal is to create a user interface where users can select options from a drop-down list and receive corresponding output based on their selection. The drop-down list options are populated using data from a JSON file, and the desired output is derived fr ...

Shopping Directive Coverage Discrepancy

In my application, there is a shop item directive that includes a price attribute. When a user interacts with the directive, the total cost (a variable stored in the main controller) should be updated by the price of the item that was clicked. Unfortunate ...

Framer motion layout animation fails to account for page scrolling during transitions in NextJs routes

Currently, I am working on a fascinating NextJS project that showcases a series of interactive blocks. As the user navigates through the app, these blocks dynamically adjust their size and position on the screen. To achieve this effect, I'm leveragin ...

Sending the HTML input value to a Knockout view

Can someone assist me with a dilemma I'm facing? Within CRM on Demand, I have a view that needs to extract values from CRM input fields to conduct a search against CRM via web service. If duplicate records are found, the view should display them. Be ...

Exploring through a dynamically generated table containing JSON data

I have successfully implemented a dynamic HTML table that is populated with JSON data based on the value of a variable when the "go" button is clicked. The initial population and search functionality work flawlessly. However, I encountered an issue when ch ...

The canvas is unable to render the image from the sprite sheet

I successfully drew an image representing the player, but now I'm encountering difficulties in drawing an enemy character. Despite adding alerts indicating that the program is executing the draw enemy function, the enemy character still doesn't a ...

What is the best way to integrate ngx-translate's pipe for global translation?

I'm currently utilizing the ngx-translate package in order to internationalize my Angular application. When translating text using the translate pipe like so: {{ 'title' | translate }} An issue arises when attempting to use this pipe in ot ...

Struggling with adding icons to the home screen in a Create React App?

When working with the manifest.json file, various icon sizes are specified as shown in this example: { “src”:”images/icons/apple-icon-57x57.png”, “type”: “image/png”, “sizes”: “57x57”, } In the index.html file, the ...

Discover the element's selector for the event that was triggered using jQuery

In the process of creating a lightweight real-time application, we are utilizing jQuery's event system to facilitate communication between modules. Any changes made in the DOM that affect elements outside the module are achieved through triggering eve ...

The timing is off in the Vue Animation Script

I am working on a web api project and I have a specific requirement. I want to play an animation on one of my HTML spans. The Vue returns a number, and I need that number to animate increasing from 00.00% up to its actual value. I found a JavaScript scri ...

Create waypoints on multiple elements

I am working on implementing a unique feature using a div tag with the class "dipper." <div class = "dipper"> <p>Peekaboo</p> </div> As part of this implementation, I have included a script that triggers the display of the "dipper ...