Tips for utilizing template literals with the require method: (require(`${aSpecificPath}`))

Trying to dynamically retrieve paths to images from an Array in Vue and showcase lazyloaded images with a v-for loop has raised some challenges. The code functions properly with template literals, but encounters an error stating "

cannot find module: '~/assets/path/to/image'
" when template literals are used within the require function. Is it feasible to pass dynamic paths to require? Is this issue related to Vue or JavaScript?

Here's an illustration:

<!-- The HTML -->
<template>
      <figure v-for="logo in logos" :key="logo.path" class="picture desktop-only">
        <picture>
          <source
            :data-srcset="require(`${logo.path}?webp`)"
            type="image/webp"
          />
          <source
            :data-srcset="require(logo.path)"
            type="image/jpg"
          />
          <img
            :data-src="require(logo.path)"
            class="lazyload"
            :alt="logo.alt"
          />
        </picture>
      </figure>
</template>
// The logos Array
            logos: [
                { path: "~/assets/images/berlinLogos/beuthBer.png", alt: "Beuth Hochschule für Technik Berlin"},
                { path: "~/assets/images/berlinLogos/fuBer.png", alt: "Freie Universität Berlin"},
                { path: "~/assets/images/berlinLogos/htwBer.png", alt: "Hochschule für Technik und Wirtschaft Berlin"},
                { path: "~/assets/images/berlinLogos/huBer.png", alt: "Humboldt Universität Berlin"},
                { path: "~/assets/images/berlinLogos/tuBer.png", alt: "Technische Universität Berlin"},
                { path: "~/assets/images/berlinLogos/uniPots.png", alt: "Universität Potsdam"}
            ]

This scenario works:

      <figure class="picture desktop-only">
        <picture>
          <source
            :data-srcset="require(`~/assets/images/berlinLogos/beuthBer.png?webp`)"
            type="image/webp"
          />
          <source
            :data-srcset="require('~/assets/images/berlinLogos/beuthBer.png')"
            type="image/jpg"
          />
          <img
            :data-src="require('~/assets/images/berlinLogos/beuthBer.png')"
            class="lazyload"
            :alt="logo.alt"
          />
        </picture>
      </figure>

Appreciate the assistance!

UPDATE:

Resolved with the following solution:

      <figure v-for="logo in logos" :key="logo.path" class="picture desktop-only">
        <picture>
          <source
            :data-srcset="logo.webp"
            type="image/webp"
          />
          <source
            :data-srcset="logo.path"
            type="image/jpg"
          />
          <img
            :data-src="logo.path"
            class="lazyload"
            :alt="logo.alt"
          />
        </picture>
      </figure>
            logos: [
                { path: require('~/assets/images/berlinLogos/beuthBer.png'), webp: require('~/assets/images/berlinLogos/beuthBer.png?webp'), alt: "Beuth Hochschule für Technik Berlin"},
                { path: require("~/assets/images/berlinLogos/fuBer.png"), webp: require('~/assets/images/berlinLogos/fuBer.png?webp'), alt: "Freie Universität Berlin"},
                { path: require("~/assets/images/berlinLogos/htwBer.png"), webp: require('~/assets/images/berlinLogos/htwBer.png?webp'), alt: "Hochschule für Technik und Wirtschaft Berlin"},
                { path: require("~/assets/images/berlinLogos/huBer.png"), webp: require('~/assets/images/berlinLogos/huBer.png?webp'), alt: "Humboldt Universität Berlin"},
                { path: require("~/assets/images/berlinLogos/tuBer.png"), webp: require('~/assets/images/berlinLogos/tuBer.png?webp'), alt: "Technische Universität Berlin"},
                { path: require("~/assets/images/berlinLogos/uniPots.png"), webp: require('~/assets/images/berlinLogos/uniPots.png?webp'), alt: "Universität Potsdam"}
            ]

Answer №1

If you want to avoid using rquire() in the template, you can follow this alternative method:

logos: [
                { path: require('../src/assets/images/berlinLogos/beuthBer.png'), alt: "Beuth Hochschule für Technik Berlin"},

Make sure to use a relative path like ../ for the image path.

Then, in the template section, include the following:

  :data-src="logo.path"

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 is the best way to transfer my object along with its unique textures from Blender to ThreeJS?

I've been using the STL Loader in three.js to import objects from Blender, but I'm facing an issue where the textures are not appearing. I suspect it has something to do with the MeshBasicMaterial of the object. I attempted to switch it to Phong ...

Issues encountered when selecting table data for filtering

One issue I am facing is with my HTML table that contains a lot of data. I have created a select option to filter the table and display the filtered data. The select options are based on the "route" column, with only three options available: Marikina, Mont ...

Is there a way to verify if a mixin has been successfully applied to the component?

I am currently conducting tests on a VueJS 2 application using the vue-test-utils library. I am striving to verify whether the specific component has received the mixin. This involves mounting the component utilizing the mount function and then attempting ...

The alphaMap I'm using doesn't seem to be achieving the desired transparency in my material

I am attempting to create a chainlink surface using 2 textures. The first texture is a standard map that gives the metal links a metallic appearance against a white background (diffuse): The second texture is an alpha map: My attempt to apply both textur ...

javascript - Add a function to an array, iterate through, and delete once executed

I've been attempting to develop an array that stores all pending error messages appearing on the DOM using jQuery. My goal is to iterate through the array to check for any error messages to display, and then remove them after execution. However, I&ap ...

Navigate through an overflowing element in react/next

I have a component with a fixed width and overflow-x-auto. I want to hide the scroll bar and replace it with arrow buttons for scrolling left and right. How can I add this functionality to my component? Here is the code for my component: <div className ...

How can I center align my loader inside app-root in Angular2+?

I've successfully added a basic spinner to my <app-root> in the index.html file. This gives the appearance that something is happening behind the scenes while waiting for my app to fully load, rather than showing a blank white page. However, I& ...

Exploring Grails Assets, Redirections, Secure Sockets Layer, and Chrome

Using Grails 2.1.1 with the resources plugin, I have encountered an issue when incorporating the jstree library which comes with themes configuration: "themes":{ "theme":"default", "dots":false, "icons":true } The JavaScript in the library locat ...

Activate vertical scrolling in JavaScript when an image is clicked

I currently have a collection of button images with different hover effects specified like this: <img src="home.PNG" onmouseover="this.src='homemo.PNG'" onmouseout="this.src='home.PNG'" /> My goal is to make them scroll down to ...

Unable to dynamically display images on Vuejs carousel

I recently created a carousel using bootstrap-vue with a for loop and an array of objects to dynamically generate the components. Each slide contains text and a background image. Although I successfully rendered the text dynamically, I encountered an issue ...

What is the best way to extract data from a proxy in VUE3?

Currently, I am utilizing the ref() function to store data retrieved from Firebase. However, when attempting to filter and retrieve a single record, the outcome is not as expected. Instead of returning a single object, something different is being displaye ...

Tips for maintaining table elements in place using JavaScript

My goal is to keep the tags within the table fixed when printing. The code I've written functions correctly in View mode, however, when printed using JavaScript, if one of the columns is too large, the rest of the columns get displaced. I want all col ...

Verifying if a dropdown option has been chosen through validation in JavaScript

Currently, I am working on implementing a validation block in my JavaScript code to ensure that users have selected a value before proceeding. If a value is not selected, I want to display a pop-up message prompting them to do so. function validate(form) ...

The installation of npm was unsuccessful due to a failure in the postinstall script of [email protected]

When running the command 'npm install,' I encounter the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa94959e9f979594bacbd4cbc2d4c3">[email protected]</a> postinstall C:\Use ...

Use ajax, javascript, and php to insert information into a database

Issue at Hand: I am trying to extract the subject name from the admin and store it in the database. Following that, I aim to display the query result on the same webpage without refreshing it using Ajax. However, the current code is yielding incorrect outp ...

Hover over to reveal sliding menu

Hey everyone! Take a look at this code snippet: <body> <div id="slidemenubar"> <a href="">1</a> </div><br> <div id="slidemenubar2"> <a href="">2</a> </div> </body> When hovering over the ...

The variable declared in the useState hook is not being properly updated within the callback function

const ModifiedTweet = ({ tweet, checkedList, setCheckedList }) => { const [isChecked, setChecked] = useState(false); useEffect(() => { if (checkedList.length === 0) { setChecked(false); } }, [checkedList, isChecked]); return ( ...

Gatsby MDX fails to locate the desired page despite displaying the title and slug

Currently diving into the world of Gatsby and I've decided to implement MDX for my blog pages. Following a helpful tutorial here on programmatically creating pages. All seems well as I can view them in my GraphQL and displaying the list of articles i ...

What's preventing me from drawing a line on this D3.js chart with my Angular code?

I am attempting to create a graph on my webpage using the D3.js library for JavaScript. I am able to draw a line on an SVG using HTML, but when I try to draw a line using JavaScript, I encounter the error message: ReferenceError: d3 is not defined. Even t ...

What could be the reason for Angular showing the raw HTML code instead of

I'm currently diving into Angular and encountering an issue where my HTML isn't properly displaying the values I've set. It appears to only show the raw HTML. Here's a snippet from my HTML page: <p>to-do-items works!</p> < ...