I'm having trouble getting images to load in Electron consistently. I'm using Electron Forge with the webpack template https://www.electronforge.io/templates/webpack-template
My src directory looks like this:
├── images
│ └── black.png
├── index.css
├── index.html
├── index.js
├── main.js
└── renderer.js
My HTML code looks like this:
<img src="images/black.png">
I'm using copy-webpack-plugin
to copy the images
directory.
When running in development (npm run start
) the root of the dev server is .webpack/renderer
so the image loads. When running in production (npm run package
) the HTML file is being opened from the file system so the image tag is trying to access .webpack/renderer/main_window/images
which is the wrong location and it doesn't load.
I have gotten it to work in both development and production by doing:
<img src="../images/black.png">
This is a hacky way and isn't correct to the way the files are stored in the src directory. This is something that should be simple but I've spent hours trying to figure it out and don't have a real solution yet.
I've seen a solution expressed in these links but I could not get it to work in both development and production without putting "../" in front of the path.
https://github.com/electron-userland/electron-forge/issues/1196
https://github.com/electron-userland/electron-forge/issues/941
I can think of a few ways to solve this:
- The webpack config needs to know via some kind of environment variable or flag if it is running in development or production and change the copy-webpack-plugin's "to" path.
- Change the development server to run so its root is
.webpack/renderer/main_window
I've seen the recommendation to import the image into renderer.js
but I have a few thousand images. Should I do it like this?
import './images/1.png';
import './images/2.png';
import './images/3.png';
// ...
import './images/1000.png';
Is there a way to programmatically import? Something like:
let imageMap = {};
for (let i of Iter.range(1, 1001)) {
let image = import(`./images/${i}.png`);
imageMap[i] = image;
}
Then how would I refer to it in HTML? Can it be done without DOM editing code?
I prefer not to import my images into my JavaScript file and run them through webpack loaders. I just want to reference static files from my HTML code in a way that works in both development and production.
I also have a 5MB JSON file that I need to access using fetch()
. I tried to import this through a loader but the build process took more than 5 minutes and I killed it.
Loading static files is a basic part of making web pages and should be a part of the project template unless I am missing something super obvious.