Dynamic import with require in Vue webpack not functioning as expected

Currently, I am in the process of developing an app that will be able to play various sounds. To achieve this functionality, I have created a NoiseMix component that will contain multiple Noise components. Each Noise component must have its own URL parameter in order to load the corresponding mp3 file. However, I have encountered some difficulties with handling static files.

Within the NoiseMix component, I have defined the following data:

data: () => {
    return {
        sounds: [
            {   id: 1,
                url: "/assets/sounds/rain.mp3",
                icon: "fas fa-cloud-rain",
                name: "Rain",
                volume: 50
            }, {
                id: 2,
                url: "/assets/sounds/rain.mp3",
                icon: "fas fa-wind",
                name: "Wind",
                volume: 50
            }, {
                id: 3,
                url: "/assets/sounds/rain.mp3",
                icon: "fas fa-water",
                name: "Waves",
                volume: 75
            }
        ]
    }
},

The structure of my Noise Component is as follows:

<template>
    <div class="single-noise">
        <div class="single-noise__icon">
            <i :class="icon"></i><br />
        </div>
        <div class="single-noise__content">
            ID: {{id}}<br />
            Name: {{name}}<br />
            Sound URL: {{url}}<br />
            Volume: {{volume}}<br />
            <input type="range" min="0" max="100" name="" v-model="volume"><br />
            audio:
            <audio controls>
                <source :src="trackUrl" type="audio/mpeg">
            </audio>
        </div>
    </div>
</template>

<script>
export default {
    name: "Noise",
    props: {
        url: String,
        icon: String,
        name: String,
        id: Number,
        volume: Number,
    },
    computed: {
        trackUrl () {
            // THIS LINE IS THE PROBLEM
            // If I use require('@' + this.url); the app doesn't load at all and there's no error
            return require('@' + '/assets/sounds/rain.mp3');
        }
    }
}
</script>

Answer №1

To ensure Webpack handles dynamic imports correctly, some additional configuration may be necessary (it seems the problem could be related to using the alias independently without thorough testing.) Give this a try:

return require('@/assets/sounds/' + this.filename)

Although it may appear similar to your existing code, this adjustment should deliver the desired outcome.

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

Using the hover event in a jQuery plugin: A step-by-step guide

A star rating plugin I am developing is encountering an issue with implementing the hover event. jquery, (function($){ $.fn.extend({ rater: function(options) { var defaults = { } var options = $.exten ...

Error message: jQuery AJAX request fails due to permission denial issue on Internet Explorer

I am facing a major challenge on my website. I have implemented AJAX to update the content of a DIV, which works perfectly on all pages except for some links under the Portfolio tab. The links for "photography", "interactive", "print", and "traditional" tr ...

Storing HTML table data in a MySQL database will help you

Operating a website focused on financial planning where users can input various values and cell colors into an HTML table. It is crucial to uphold the integrity of these HTML tables. How can I store the complete HTML table (including values and colors) i ...

Starting from TypeScript version 5.6, `Buffer` cannot be categorized as either `ArrayBufferView` or `Uint8Array | DataView`

Struggling to make the transition to TypeScript 5.6 Beta, I am encountering these error messages within the node_modules directory. Without making any other modifications, how can I resolve these errors? node_modules/@types/node/buffer.d.ts:632:19 - error ...

Utilize a standard PHP script for every subdirectory within a domain

I'm currently working on a website and the design I'm using involves changing the URL in the address bar using the history API when the page content changes through JavaScript and AJAX. However, I also want each "page" of the website to be access ...

Server-side rendering or updating of React elements

One issue I am facing in my React app is that while all components can update themselves through the browser, a specific module called jenkins-api only functions when called server side. To retrieve the data and pass it into my template, I have utilized th ...

Is it possible to use jQuery validate for remote parsing with two fields in a single call

Currently, I am facing an issue while trying to parse two values using jQuery's validate plugin to compare with an SQL database. The DateReceived value is successfully parsed, but the CentreID value always appears as null. Below is the code snippet I ...

Remove an object based on its unique identifier with the help of mongoose

I am working on developing an API to delete a document in MongoDB using Mongoose. Below is the route I have created: router .route("/tasks") .delete('/:id', function (res, err) { taskSchema.findByIdAndRemove(req.params.id, (err, ...

What are some effective techniques for handling asynchronous operations while utilizing [displayWith] in an autocomplete

In my angular reactive form, I am struggling with an autocomplete functionality. I want to show the name (myObject.name) but use the ID (myObject.id) as the value. However, when the form is populated with existing values, there is a delay in retrieving th ...

Using Firebase onDisconnect with React Native

I am currently working on a React Native app and I am facing an issue where I need to update the user status to 'offline' in Firebase when the user closes the app. Here is what I have tried: import React, { Component } from 'react' ...

I'm facing an issue where Typescript isn't recognizing Jest types

The Challenge Setting up a TypeScript project with Jest has been proving difficult for me. It seems that TypeScript is not recognizing the Jest types from @types/jest, resulting in an error message like this: Cannot find name 'test'. Do you nee ...

When a variable is used, the .sort() method does not effectively organize the elements

When working with Nodejs and mongoose queries, I encountered an issue with using the .sort() method dynamically based on user input. While it works fine when hardcoded, I want to use a variable to determine the sorting order. However, when attempting to do ...

I am wondering how to create a heartbeat using 3.JS and Leap Motion technology

Recently, I created a scene featuring my 3D model of a heart, imported from Blender. Integrating it with a Leap Motion device allows users to control the movement and rotation of the heart model. My goal is to implement a function that will cause the hea ...

How can one correctly import node modules in the handler function of next.js API?

I need to import bcrypt in a file located in my /api directory. // pages/api/login.js const bcrypt = require('bcrypt'); export default async function handler(req, res) { switch (req.method) { case 'POST': // do stuff with b ...

Expanding URL path parameters in Angular's ui-routerWould you like to

Can UI-router handle this type of routing? Parent state - /saved/:id Child state - /saved/:id/eat Here is the code snippet I am using. However, when I attempt to access it, the page redirects: .state('fruits.banana.saved', { url: &apo ...

What steps do I need to take to create a custom image for a website?

I'm looking for a way to create a website image using just code, without the need for an actual image file or image tag. Is there a method to do this? Would I use CSS, Javascript, or HTML5 for this task? If using JavaScript to dynamically generate the ...

How can we guide the user to a different page when a particular result is retrieved by AJAX?

Whenever my PHP function makes a database call, I receive multiple results. The ajax then displays these results in a div element. My question is: How can I redirect the user to the next page once I obtain a specific result from the PHP function? Current ...

Issue with redrawing pie chart positions in vue2-highcharts

For my project, I am creating a 3-pie chart using a single Highchart in a resizable container with VueJs and the vue-highcharts component. To achieve this, I need to adjust the positions and sizes of the pies whenever the container is resized. However, I a ...

Having trouble sending serialized data using jQuery Ajax in IE6

When I use the jQuery AJAX command to post data in Internet Explorer 6 and then try to print the data with print_r($_POST), PHP prints an empty array. How can I post submitted data to PHP? I'm not sure what the issue is in IE6. To alert this data ...

Javascript: Harnessing Textbox Arrays for Improved Functionality

Check out the form displayed below. <form id="upload_form" enctype="multipart/form-data" method="post"> <input type="text" name="name[]" id="name"><br> <input type="text" name="name[]" id="name"><br> <input type="fil ...