I have two files that both need a global variable. I have a click button. When it's clicked, runs a function. The code looks like this:
file1:
var globalVar = '', // The global variable
<button onClick = {() => this.edit(arg1)}></button>
function edit (arg1){
globalVar = arg1;
}
module.exports = globalVar;
I have another file, looks like this:
file2:
var globalVar = require(./file1);
function openModal(){
if (globarVar != ''){
do something
} }
The issue is that when I click button, the globalVar is updated in the edit() function, but I console.log(globalVar) in file2 it shows ' '.My question is how do I pass the globalVar to file2 when I click the button?
A global variable is accessible to all functions in every source file where it is declared. To avoid problems: Initialization — if a global variable is declared in more than one source file in a library, it should be initialized in only one place or you will get a compiler error.
To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
start was called. Global variables can only be shared or inherited by child processes that are forked from the parent process.
The best way to share global variables across modules across a single program is to create a config module. Just import the config module in all modules of your application; the module then becomes available as a global name.
If you truly want a global variable (not advisable, of course) then you're always 100% free to do
window.globalVar = 0;
in any of your modules.
The more robust solution would of course be to have this global variable sit in some sort of dedicated module, like
globalVar.js
export default {
value: 0
};
and then you could
import globalVal from './globalVar';
globalVal.value = 'whatever';
from any modules needed.
The only risk would be that webpack might duplicate this same "global" value into multiple bundles if you're code splitting, depending on your setup. So separate module would be using their own local copy of this not-so-global variable. EDIT - this isn't true. webpack never did this; that comment was based on a misunderstanding on my part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With