I spent a few hours chasing down just how to get my static assets (css, fonts, images) to load in an Electron app built using electron-forge v6 (https://www.electronforge.io/) and its webpack plugin (https://www.electronforge.io/config/plugins/webpack) while in development mode. There really isn't any documentation available online, either in the electron-forge documentation or in places like blogs or gists or stackoverflow. So I thought I'd put it down here.
Load CopyWebpackPlugin
npm i -D copy-webpack-plugin
Use the plugin to move your directories into place.
It's important that they be at bare minimum in .webpack/renderer
, since that is the root used for localhost
webpack.renderer.config.js
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const assets = [ 'img', 'css', 'fonts' ]; // asset directories
module.exports = {
// Put your normal webpack config below here
module: {
rules: require('./webpack.rules'),
},
plugins: assets.map(asset => {
return new CopyWebpackPlugin([
{
from: path.resolve(__dirname, 'src', asset),
to: path.resolve(__dirname, '.webpack/renderer', asset)
}
]);
})
};
Files without absolute paths do not appear to work, even when everything is relatively placed.
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="/css/main.css">
</head>
<body>
<img src="/img/img_src.png" />
<p style="font-family: MyFancyFont, sans-serif;">👆 that's an image!</p>
</body>
</html>
Thanks for this, I was banging my head on this for a few hours and your post helped me out.