Troubleshooting Vue.js dynamic image path loading issues

Struggling to dynamically load images in a single file component, I keep encountering an error stating that the module cannot be found. It seems like I'm attempting something similar to what was discussed in this post on Stack Overflow, but I can't pinpoint where my mistake lies. My project was set up using the webpack template.

Below is the relevant code snippet from my template:

<router-link :to="{ name: 'JobsDetail', params: { slug: job.slug } }">
    <span class="icon">
        <img :src="getIconPath(job.slug)"/>
    </span>
    {{ job.title }}
</router-link>

This is the function I'm utilizing to retrieve the image:

methods: {
    getIconPath (iconName) {
        const icons = require.context('../assets/', false, /\.png$/)
        return iconName ? icons(`./${iconName}.png`) : ''
    }
}

The images are stored in the /src/assets/ directory. The error message displayed in the browser console reads:

[Vue warn]: Error in render: "Error: Cannot find module './some-icon.png'."

I'm uncertain whether this issue stems from a webpack configuration problem or if it's related to the getIconPath function itself. Any assistance would be greatly appreciated. Thank you!

Answer №1

If your JavaScript code is located at /src/components/JobList.vue and your images are in the directory /src/assets/, you can use the following method:

methods: {
    getIconPath (iconName) {
        return iconName ? require(`../assets/${iconName}`) : ''
    }
}

Answer №2

It appears that when webpack builds in development or production, the static assets like images should be directed to /static.

In the configuration file found at vuejs-templates/webpack/blob/develop/template/config/index.js, you will find the default configuration as follows:

// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',

Based on this information, the src attribute for images should be something similar to:

<img src="/static/whatEverMyIconIs.png"/>

Further examination of the configurations in vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js reveals a url-loader plugin specifically designed to place images into /static/img:

 {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: utils.assetsPath('img/[name].[hash:7].[ext]')
    }
  },

This may result in your image src URL looking something like:

<img src="/static/img/whatEverMyIconIs.png"/>

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

Autocomplete like Google with arrow key functionality

I have developed a basic search engine that retrieves data from a MySQL database using the PHP "LIKE" function (code provided below). Everything is functioning correctly, but I would like to enhance it so that users can navigate search results with arrow k ...

Clicking on a JQuery dropdown menu will always result in it staying open

After creating a dropdown menu click, I noticed some strange behavior. When I click the dropdown button, the menu appears as expected. However, if I move my cursor away without clicking the button again, the dropdown menu disappears and behaves like a hove ...

How can I ensure that the ons-scroller stays at the bottom when writing a JavaScript code in Onsen UI?

How can I ensure the ons-scroller stays at the bottom when writing JavaScript? This is the code I am using: <ons-page> <ons-toolbar> <div class="left"><ons-back-button>Return</ons-back-butto ...

Tips for retaining the original size of an image in HTML5 canvas drawImage

function getBase64ImageData(_id) { var canv = document.createElement('CANVAS'); var context = canv.getContext("2d"); var imageElem = document.getElementById(_id); context.drawImage(imageElem, 0, 0); var dataURL = canv.toDat ...

Unlocking the secrets of extracting dimensions from imported SVG components in nextJS

I am facing an issue with importing an SVG file as a component and trying to obtain its dimensions, but it keeps returning null. Can someone provide me with advice on how to resolve this? PS. When I try using getBBox(), it throws an error. Here is the co ...

Tips for retrieving the text value on keyboard enter press without triggering form submission

I am currently working on a feature where hitting the Enter key in a textbox should not automatically submit the form. The textbox is located within a form: @Html.TextBoxFor(model => model.ID, new { @class = "form-control input-sm", placehold ...

Ways to evaluate the amount of traffic on a webpage?

Recently, I encountered an issue while creating a page to showcase blog posts. Each post had the typical social media share buttons like "Facebook like," "tweet this post," and "+1." Additionally, there were some extra JavaScript functions added for variou ...

Substitution of "with" operator in strict mode

Let's say I have a user-entered string value stored in the variable f. For example: f = "1/log(x)"; In vanilla JavaScript, I used the following operator: f = "with (Math) {" + f + "}"; While this code worked perfectly fine in vanilla javascript, i ...

What is the best way to iterate over a multidimensional array in Angular/Ionic?

I've been struggling to find a solution tailored for looping in a .ts file instead of HTML. My main objective is to iterate over an array and compare the entered value with the keys. If there's a match, I want to retrieve the values stored withi ...

Using Vue to fetch JSON data with Axios

When trying to retrieve user data from a MongoDB in JSON format using axios.get within a Vue.js application, my aim is to visualize this data by iterating through all user objects in the users array. The issue I'm facing is that each character is trea ...

Adding a new key-value pair to a JSON data structure

Here is the JSON object that I am currently handling: { "name": "John Smith", "age": 32, "employed": true, "address": { "street": "701 First Ave.", "city": "Sunnyvale, CA 95125", "country": "United States" }, ...

What is the best method for adding files to JSZip from a remote URL?

Is it possible to load files into a Zip folder from a specified URL? For example: var zip = new JSZip(); zip.file("file.txt", "/site.net/files/file.txt"); Update I am following this example: I attempted the code provided but it was unsuccessful. I do ...

What is the best way to implement onChange for multiple form fields in Reactjs?

Can anyone help me troubleshoot my form? I'm having issues with typing into the fields and nothing happens when I try. Initially, whatever text I input would show up in all the fields simultaneously, but after making some changes, it stopped working ...

Navigating in next.js

Whenever I run my program, it displays the following error message: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component ...

Learn the process of transferring information from a dynamically generated table to a database using PHP

After creating a table using PHP dynamically, I am facing an issue with updating some cell values based on user input. I have provided my code below. I tried using [] in the names attribute to make names an array as suggested on Stack Overflow, but it didn ...

Creating multiple nested ng-repeats in an AngularJS table

Managing a large amount of data on users' availability by hour for multiple days can be challenging. The data is structured as follows: availData = { "date1":arrayOfUsers, "date2":arrayOfUsers, ... } arrayOfUsers= [ userArray, userArray, ... ] user ...

Photoswipe is encountering an error because the Navigator is not defined in the .css/.scss files

I have an outdated vuejs 2 project from around 2018-2019 that I'm trying to compile. Running yarn build results in the following error: https://i.stack.imgur.com/IiRzy.png Within the project's /src folder, there are instances of navigator, but ...

Discover a JavaScript table using a for loop

Currently, I'm in the process of setting up a search bar within a table that has been populated by looping data retrieved from an API. My goal is to allow users to search for specific entries either by name or email. Unfortunately, I seem to be encoun ...

Unable to retrieve information from the wiki API

Here is the link to my codepen project: https://codepen.io/mlestina/pen/OZpOQW?editors=1111 I am having trouble retrieving data from the Wiki API. When I check the Contr-Shift-J readout, I see: Loading failed for the <script> with source “https: ...

What is the method for arranging objects in AngularJS using a custom sorting sequence?

I would like to display an array of object's properties in a custom sorted order. Here is the initial array: $scope.weekDays = [ { "day" : "TUESDAY", "count": 10 }, { ...