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

戏子无情 提交于 2020-01-16 09:09:07

问题


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


回答1:


switch(process.platform) {

    case 'darwin': {
      return path.join(process.env.HOME, 'Library', 'Application Support', 'template-editor', ...);
    }
    case 'win32': {
      return path.join(process.env.APPDATA, 'template-editor', ...);
    }
    case 'linux': {
      return path.join(process.env.HOME, '.template-editor', ...);
    }
}

And if you are going to get the location of your app then use this process.env.PORTABLE_EXECUTABLE_DIR But this variable will be only available when you used electron-builder to pack your app.



来源:https://stackoverflow.com/questions/59477544/how-to-require-an-image-with-react-electron-outside-of-src-folderapplication-su

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!