1

Bear with me, kind of a two-parter here. First off am I correct in thinking that if I have my main JS set up like this..

const myModule = require('./myModule');
let parentVar = 'foo';
myModule.test();

..and I set the up the required module like this..

module.exports = {
    test: ()=>{
        console.log(parentVar);
    }
}

..that when the main script calls myModule.test() it should throw an error as it can't access parentVar? This has been my experience and understanding of working with modules in traditional web builds.

Now, I'm building an Electron app (using Electron Forge) and here I can call myModule.test() and it succeeds, appearing to have access to the variable declared in the main script.

I'm trying to understand why this is and and I can see two differences that may or may not be relevant.

  1. I'm not using webpack/babel so the JS is in a raw form that I don't usually work with.
  2. My require() statements only work if I give the full path relative to the app root rather than to the file doing the requiring.

Can anyone explain why the required module can access properties of the requirer in Electron?

Can anyone explain why my require statements work only with root relative paths in Electron?

Thanks all :)

EDIT This is all happening in the renderer. The main JS is being loaded into my index.html using a standard <script> tag. It then requires the module from there.

popClingwrap
  • 3,919
  • 5
  • 26
  • 44
  • Is this code for renderer? – tpikachu Apr 23 '20 at 17:08
  • @tpikachu - Yes (have edited my question). main script loaded into index.html – popClingwrap Apr 23 '20 at 17:13
  • I see. to use `require` means you are going to use Node API at your browser – tpikachu Apr 23 '20 at 17:15
  • For this you should create browserWindow with nodeIntgeartion as true – tpikachu Apr 23 '20 at 17:15
  • Like this https://stackoverflow.com/questions/60227586/ipcrenderer-not-receiving-message-from-main-process/60227981#60227981 – tpikachu Apr 23 '20 at 17:16
  • @tpikachu - I have already done this. I had to to get `require` working in the first place. Nothing is actually broken it just seems to behave in an unusual way. I worry that if I just forge ahead without understanding _why_ that I'll shoot myself in the foot later – popClingwrap Apr 24 '20 at 09:57

1 Answers1

0

Classic easy-when-you-know-how problem.

Where I'm including my main script in the html I simply had to give the the tag a type="module". I guess without this the script was just loading into the page without any of the moduly wrappings which was why the variable were available across the board.

In my index.html the script tag now looks like this..

<script type="module" src="js/app.js"></script>

popClingwrap
  • 3,919
  • 5
  • 26
  • 44