Troubleshooting Vue.js 2: Difficulty with Vue locating files stored in the /assets directory (v-for loop)

My Vue-cli 3 project with Webpack has the following folder structure:

/public
/src
   /assets
      p1.jpg
      p2.jpg
App.vue
main.js

I have read that in order for Webpack to recognize the /assets directory, require() should be used in JavaScript files.

This code snippet works as expected:

<template>
    <div>
        <ul>
            <li v-for="photo in photos" :key="photo.id">
                <img :src="photo.imageUrls.default" />
            </li>
        </ul>
    </div>
</template>


<script>
    /* Using require() is necessary for webpack to resolve URLs in javascript */
    export default {
        data() {
            return {
                photos: [
                    {
                        id: 1,
                        caption: 'P1',
                        series: '',
                        notes: '',
                        imageUrls: {
                            default: require('./assets/p1.jpg')
                        }
                    },
                    {
                        id: 2,
                        caption: 'P2',
                        series: '',
                        notes: '',
                        imageUrls: {
                            default: require('./assets/p2.jpg')
                        }
                    }
                ]
            }
        }
    }
</script>

However, this alternative approach does not work and results in an error message in the console: "Error: Cannot find module './assets/p1.jpg'"

<template>
        <div>
            <ul>
                <li v-for="photo in photos" :key="photo.id">
                    <img :src="imagePath(photo)" />
                </li>
            </ul>
        </div>
</template>


<script>
    /* To resolve URLs in javascript using webpack, require() function is needed */
    export default {
        data() {
            return {
                photos: [
                    {
                        id: 1,
                        caption: 'P1',
                        series: '',
                        notes: '',
                        imageUrls: {
                            default: './assets/p1.jpg'
                        }
                    },
                    {
                        id: 2,
                        caption: 'P2',
                        series: '',
                        notes: '',
                        imageUrls: {
                            default: './assets/p2.jpg'
                        }
                    }
                ]
            }
        },
        methods: {
            imagePath(photo) {
                return require(photo.imageUrls.default);
            }
        }
    }
</script>

Can someone help me understand what is incorrect in the second example? I am reluctant to use require() inside the data, as it may come from a server, which feels strange. Thank you.

EDIT: Following Edgar's recommendation, I have placed my images in a folder within the /public directory since they belong to the server and not the app. This way, I no longer need to bother with require().

Answer №1

Vue.js comes with a designated public folder that is automatically generated for you when using the Vue CLI. This public folder should be used to store any assets related to your project. For more information on this topic, refer to the official Vue.js documentation.

Here is an example folder structure:

/api
/public
/public/assets
/public/favicon.ico
/public/index.html
/src
index.js
app.json

and so on...

The public folder is ideal for storing static assets like images, fonts, favicon, robots.txt, sitemap.xml, and more.

To reference these static assets, use the following syntax:

In your HTML template:

<img src="/assets/some-image.svg" alt="Example" />

Or in your component JS:

array: [
        {
          iconUrl: '/assets/some-image-1.svg',
          label: 'Some Label'
        }
      ]

If these assets are not located in the public folder, you would need to utilize require to access them from the src directory, as mentioned by others. However, it is recommended to keep assets in the /public/ folder for ease of access.

Answer №2

Ensure that you include the require statement because your asset is bundled on the client side.

If you prefer to have your asset on the server, place it in the public folder instead.

We often encounter an issue when the component is located in the components folder. In such cases, consider using:

default: require('../assets/p1.jpg')

Answer №3

In my opinion, this issue seems to be a frequently encountered one that can easily be found through a search. The suggested solution involves moving the resource file to the static directory. While files in the asset folder are typically processed by webpack without any issues in the HTML module, there may arise complications in the code module.

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

How can I deactivate the main color of the FormLabel when the focus is on the radio button group?

Is there a way to change the color of FormLabel to black instead of the primary color when the radio button group is focused? https://i.sstatic.net/h3hML.png const styles = { formLabel: { color: "#000" }, formLabelFocused: { color: "#000" ...

Using ES6 syntax to inject modules into an extended controller can result in the Unknown provider error

Currently, I am facing an issue with creating a child class ModalCtrlChild extends ModalCtrl from my controller class ModalCtrl. Whenever I attempt to do this, I encounter an unknown provider error related to the modules injected in ModalCtrl. The project ...

The position of the camera remains static even after it is attached to a mesh

Looking to implement a TPS (third-person shooter) camera that follows the player? I have added the camera to a cube which represents the player's movement. You can view the coordinates of both the camera and cube in this example. While the camera is f ...

Creating a custom class implementation in JavaScript and initializing it with a constructor function

Perhaps there is a similar question out there, but I haven't come across it yet and I'm still facing an issue. Here's what I've tried: function createClass(obj) { const constructor = obj.constructor; constructor.prototype = obj; ...

Rendering data in React using the array indexRendering data in React

I'm encountering an issue in React JS where I need to display all data from a REST API with a numeric index. REST API: [ { "id": "1", "start_date": "2020-05-08 09:45:00", "end_date": "2020-05-08 10:00:00", "full_name": "mirza", "cust_full_name": "fu ...

Deploy Node.js on a Debian server hosted on Google Compute Engine

Currently, I am operating a Debian server on Google Compute Engine using a host called example.com. My goal is to run a node.js app within a specific directory on this server, for instance, example.com/mynodeapp. Fortunately, the necessary components such ...

Passing a list variable to JavaScript from Django: A step-by-step guide

Currently, I am facing an issue while attempting to generate a chart using Chartjs and Django. The problem arises when transferring data from views.py to the JavaScript code. Here is a snippet of my code in views.py: def home(request): labels = [&quo ...

Unlocking the Power of Observable Objects with Knockout.js

Recently delving into knockoutjs, I came across the Microsoft tutorial showcasing how to integrate knockoutjs with MVC Web API. The tutorial can be found at: https://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-8. In a particu ...

Is there a way to monitor the home button press event within a PhoneGap application?

Hello! I'm curious if there is a way to track when the Home button is pressed on both Android and IOS using phonegap phonegap build. I have looked into events for the home button press, but have only found information on back button events so far. ...

Benefits of using props destructuring in React - beyond just being a syntactic shortcut

This idea might not be exclusive to React, but I've struggled to discover a compelling reason beyond concise and easier-to-read code. ...

jQuery - Incorrect folder path for image replacement

I have a specific request to change the image paths in multiple .html pages, redirecting them from the default folder to another folder. After implementing code from an external javascript file successfully, I am encountering an error where the HTML sou ...

`Integrate Passport Azure AD authentication into your GraphQL Server's Context`

Seeking assistance from experienced individuals to tackle some async JavaScript issues. I am trying to secure a GraphQL server using the Passport library and the passport-azure-ad strategy. The validation of incoming Access Tokens seems to be working fine ...

Creating a fantastic Image Gallery in JavaScript

As I work on creating a basic gallery page with html and css, everything seemed to be running smoothly. However, upon testing it in Google Chrome and IE, the onmouseover function is not responding as expected. The idea is for a larger image to display in t ...

Updating the Scale of the Cursor Circle on my Portfolio Site

I attempted to find tutorials on creating a unique circle cursor that can hide the regular mouse cursor as well. After implementing it with a difference blend mode, I encountered an issue where I wanted the scale to change when hovering over a link. The ...

What is the best way to invoke an API two times, passing different parameters each time, and then merge both responses into a single JSON object using a callback function?

This code snippet is currently functional, but it only retrieves the JSON response for the first set of parameters. I am looking to make multiple calls to an external API with different parameters and then combine all the responses into one concatenated J ...

Is it possible to utilize the System.import or import() function for any JavaScript file, or is it restricted to single module-specific files?

After reading an intriguing article about the concept of dynamic component loading: I am interested in learning more about the use of System.import. The author demonstrates a specific syntax for loading the JavaScript file of the module that needs to be d ...

What benefits can be gained from utilizing the beforeEach function within Jest testing?

I am currently immersing myself in the world of Jest by following this informative guide. Can you explain the benefits of utilizing the beforeEach function in Jest? I have a particular interest in identifying action dispatches. I believe that two segments ...

Having trouble with the second Angular directive not functioning correctly

I am encountering an issue with two directives on the same page. The first directive is functioning correctly, but the second one is not working as expected. Below is the code snippet: HTML <body class="login" ng-app="Login"> <div ng-controller ...

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' https://i.sstatic.net/a16DD.png I tried running different ng bui ...

What's the best way to ensure uniform spacing between the list items in this slider?

When using appendTo, I've noticed that the spacing between items disappears. I've tried adjusting the padding-bottom and left properties with no success. Does anyone have a suggestion for how to fix this issue? I'm at a standstill. $(&a ...