0

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.

6
  • No, require has nothing to do with the javascript language - read the answers in that link Commented Feb 13, 2018 at 22:35
  • This is a Webpack issue, not a pure JS issue. This question may be helpful. Commented Feb 13, 2018 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. Commented Feb 13, 2018 at 22:36
  • Maybe it can help you 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. Commented Feb 13, 2018 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? Commented Feb 13, 2018 at 22:46

1 Answer 1

1

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"?

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.