Electron variables defined in renderer are incorrectly available in imported modules

I am currently transitioning a script I made in Node.js to Electron. However, I am encountering a problem with variable scope. Variables defined in my Node.js script are not available in my modules unless they are passed or assigned. However, in electron if I declare a variable it will be available in all of my modules without passing or assigning it. For example this Node.js script will correctly fail:

// index.js
var myModule = require('./src/myModule.js');
var myString = 'string';
myModule.run();

// myModule.js
exports.run = function() {
    console.log(myString); // Correctly says myString is undefined because it is not declared in myModule.js
}

However, the same code in Electron will print the variable defined in renderer.js:

// renderer.js
var myModule = require('./src/myModule.js');
var myString = 'string';
myModule.run();

// myModule.js
exports.run = function() {
    console.log(myString); // Prints 'string' even though it is not declared in myModule.js
}

How can I prevent the variables defined in renderer.js from being available in my modules. I find it makes it very easy for me to create unorganized code.

Upvotes: 4

Views: 621

Answers (1)

Hrun
Hrun

Reputation: 116

You need to define the type of your script as module in your html.

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

Otherwise renderer.js will use the global scope to save your variable, which is why it was available for myModule.js in your example.

But you can also notice that variables defined in myModules.js will use, like you expect, the local scope. That's because only scripts loaded via the tag will use the global scope.

So another option to do this would be to create a renderer.js which consists only of

// renderer.js
require('./index.js');

and your original nodejs files should work as expected:

// index.js
var myModule = require('./src/myModule.js');
var myString = 'string';
myModule.run();

// myModule.js
exports.run = function() {
    console.log(myString); // myString is now undefined
}

But you should be aware that variables defined inside of renderer.js will still use the global scope.

Upvotes: 3

Related Questions