How to require an image with react electron outside of src folder(Application Support)

I want to require images dynamically from the Application Support folder. I use the react-app-rewired package to require outside of the src folder but when I use a window variable in the image src I get the error: Error: Cannot find module. I get the path like this and get an error code with a string that works when I use it directly in the src part of the image tag.

window.path = window.electron.remote.app.getPath("appData")

image(Does not work):

<img className="topSvg" src={require(""+window.path+'/current/'+this.props.project+'/src/content/img/changeable/'+data.top.img)} alt="top_svg"/>

Error: Cannot find module '/Users/tobi/Library/Application Support/template-editor/current/Tobi/src/content/img/changeable/top_svg.svg

image(works):

<img className="topSvg" src={require('/Users/tobi/Library/Application Support/template-editor/current/Tobi/src/content/img/changeable/top_svg.svg')} alt="top_svg"/>

I also tried to just replace the window.path with the string ‘/Users/tobi/Library/Application Support/template-editor’ which also works fine
Also here: https://stackoverflow.com/questions/59477544/how-to-require-an-image-with-react-electron-outside-of-src-folderapplication-su

hi,

I had the similar need to access image on user’s directory.
To serve static file with absolute url, specially when using react/vue/angular you want to register and use a new protocol. (file: won’t work)

Depend on electron version >= 5.0 is a little different, this is for 7.0. I’m registering “root” which point to the root of the system (’/’ under linux, on win you’ll add drive letter on the url)

On your main.js :
``
const {app, protocol} = require(‘electron’)

// declare the scheme; has to be done before creating the main window
protocol.registerSchemesAsPrivileged([
{scheme: ‘root’, privileges: {standard: true, secure: true}}
])

// register the protocol, just prepend your absolute url with “root://”
app.on(‘ready’, () => {
// access to the root of the system, policy of some framework may prevent the use of file://
protocol.registerFileProtocol(“root”, (request, callback) => {
let url = request.url.substr(7)
if (url[url.length - 1] == “/”) {
url = url.substr(0, url.length - 1)
}
callback({path: url})
}, (error) => {
if (error)
console.error(‘Failed to register protocol root’)
})
}
``

You can also put window.path, prop project, etc into the protocol which will shorten to :
<img className="topSvg" src={'root://src/content/img/changeable/'+data.top.img} alt="top_svg"/>

That’s the basic, just adapt to your needs.

But why does it work when I just use the direct string instead of using the variables without using this new protocol see the second img tag in my post