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.
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.
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>