ElectronJS: Renderer can't resolve module require("./index.js") over HTTP

I have my folder structure set up like this:

assets/
  logo.png
  other_web_assets.png
electron/
  node_modules
  main.js
  package-lock.json
  package.json
src/
  index.js
  otherJavascriptFiles.js
index.html
style.css

The reason I've separated ElectronJS from the website is that the website is intended to be served via HTTP (it's not supposed to work without Electron though, I only need the HTTP protocol for Firebase Authentication). Currently I'm serving index.html via the LiveServer VSCode extension on port 5500.

In my index.html I'm using require("./src/index.js") to load index.js, and in the index.js file I use require to communicate with the other javascript files and other node modules.

However, the require("./src/index.js") doesn't work from index.html, I always get the error Uncaught Error: Cannot find module './src/index' in the dev tools console. I've tried importing index.js with <script src="./src/index.js"></script>, but that results in the same error, with a different javascript file that my index.js tries to import using require.

I can however require normal node modules (for example require("request")) without any errors.

Is there any way to fix this?

1 answer

  • answered 2020-09-24 15:43 Jose Cabrera Zuniga

    To import functions from a js file I use

    import {functionName} from 'path to js file where function is defined'
    

    I use Require for pictures, etc. but not for js files.

    I suggest you to use import. Also, define the functions you need to import into other files using the word export