Unable to require() a variable path from props in VueJS

Tags: , ,



I am sending data – a URL to a local image file, from parent to child, and when I load it in child component’s it shows an error, but if I directly load it, it works.

Code:

In parent.vue component’s data:

data(){return{items:[
      {id:1, src:"../../../assets/img.png" }

In child.vue component’s mounted()

img.src = require(this.item.src); // This does not work
img.src = require("../../../assets/img.png") // This works

And console.log(this.item.src) gives exactly the same string, so the child is actually getting the data correctly

As you can see both those examples have the same URL string, but one works, one does not. I have tried every combination or relative Url but everything fails.

What’s going on?

note: I am serving the development version via webpack-dev-server

Answer

The problem should be that require is handled by webpack statically during compile time, whereas the value in the prop resolves during runtime

img.src = require(this.item.src); // This does not work since during webpack build the path is not resolved
img.src = require("../../../assets/img.png") // This works since the image is loaded and added statically

See this answer for more clarity webpack dynamic module loader by require

You could try using the dynamic import syntax for loading the image with a variable, but the webpack configuration [may] have to be modified, if you aren’t using the vue cli

it would be something like import(this.item.src).then(src => img.src=src); but should be called in the mounted() function, maybe



Source: stackoverflow