-1

I have an image tag:

<img :src="getImage(file.path)">

that dynamically requires an image src by calling this method:

getImage(value) {
  return require(value)
}

The problem is, it only works when I specify the string directly in the require() function.

I tested it by using a hardcoded value rather than the input value just to see what's going on. Could you please explain why does this below happens?:

Works

  getImage(value) {
    return require('C:/Users/name/Desktop/1.png')
  }

Doesn't work

  getImage(value) {
    var image = 'C:/Users/name/Desktop/1.png'
    return require(image)
  }

throws this error: Error: Cannot find module "."

So it doesn't allow me to use that input value because it only works with a string directly specified in the required()


UPDATE

If require() is not the way I should be loading images in JS, please could you tell me how do I do it in JS?

P.S. it's an Electron project, opened on localhost with webpack's server.

Un1
  • 3,874
  • 12
  • 37
  • 79
  • No, require has nothing to do with the javascript language - read the answers in that link – Jaromanda X Feb 13 '18 at 22:35
  • This is a Webpack issue, not a pure JS issue. [This question](https://stackoverflow.com/questions/37241662/using-require-with-a-variable-vs-using-a-string-in-webpack/37241982) may be helpful. – lonesomeday Feb 13 '18 at 22:36
  • @Un1: It might be part of some language that compiles to JS, or of whatever JS library you're using (though in that case it wouldn't matter whether the string was a literal or a variable), but it's not part of JS proper. – cHao Feb 13 '18 at 22:36
  • Maybe it can help you https://github.com/facebook/react-native/issues/6391 . If you want to load image dynamically you should send http request on server and get image from server side. – Sergey Feb 13 '18 at 22:37
  • Guys it's an electron app, there's no server, i'm just trying to dynamically load an image with JS, what am I doing wrong there? – Un1 Feb 13 '18 at 22:46
  • No need for wrapping it with `require` call. Just return the resource's URL. – CM. Feb 13 '18 at 23:24

1 Answers1

0

require does not run on the browser. It is compiled and therefore can't take a runtime variable. The link in the comments explains more.

What is this Javascript "require"?

Jeff
  • 24,623
  • 4
  • 69
  • 78
  • Could you please tell me then, how do I load an image in JS? Do I still use the `:src="functionName(path)"` to load an image? Or there are better ways? – Un1 Feb 13 '18 at 22:39
  • 1
    Your function should just return the image source as a string and the browser will load it for the user. I think you can also load images in js with the Image class but you probably don’t need that – Jeff Feb 13 '18 at 22:46
  • I realized that I'm doing it completely wrong, could you delete your answer please so I can delete the question so that it doesn't confuse people? – Un1 Feb 15 '18 at 19:03