Skip to content

Instantly share code, notes, and snippets.

@Kvisaz
Forked from bbudd/assets.md
Created April 2, 2020 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kvisaz/0d8cda2087c0ff5fa7adf5c641c27436 to your computer and use it in GitHub Desktop.
Save Kvisaz/0d8cda2087c0ff5fa7adf5c641c27436 to your computer and use it in GitHub Desktop.
Loading static assets using electron-forge v6 and the webpack plugin

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.

Step 1

Load CopyWebpackPlugin npm i -D copy-webpack-plugin


Step 2

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)
      }
    ]);
  })
};

Step 3

IMPORTANT: Access files with absolute paths

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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment