Search code examples
reactjswebpackelectronelectron-forge

Using Static Assets in Elecron + React


I am new to Electron, and I have been having some trouble trying to do something simple in an Electron + React application. All I want to do is: Load a 3D model (.glb) located in my src/assets directory from a React component. I created the project using this guide. In a typical React project, I can just import the file directly in my JS module and reference the path in my code. However, with the default Webpack config, the file can't be found. There's obviously a gap in my understanding on how React + Webpack work when loading assets. What am I missing? Any help is greatly appreciated.

Thanks!


Solution

  • Turns out, the Webpack documentation spells out the answer clearly. Who knew? I found a lot of similar questions/answers for older versions of Webpack, so I'll post one here for Webpack 5. It requires a trivial two-line addition to the webpack.rules.js file:

    {
        test: /\.(png|jpg|gif|svg|glb)$/,
        type: 'asset/resource'
    }
    

    The key is the asset/resource line. It's new to Webpack 5 and allows the bundling of assets without needing any additional loaders. With that, assets can be included as Javascript modules and Webpack will take care of the rest.

    So, one can do:

    import modelSrc from "../assets/some_awesome_model.glb";
    

    And that's that. Webpack will spit out a URL such as /9feee593dc369764dd8c.glb, meaning Webpack has located and processed the asset.