Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I share a global variable between multiple files?

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?

like image 372
Bo Huang Avatar asked Sep 28 '17 18:09

Bo Huang


People also ask

Can global variables be accessed by multiple files?

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.

How do I share global variables across modules?

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.

Can global variables be shared between processes?

start was called. Global variables can only be shared or inherited by child processes that are forked from the parent process.

How do you pass a global variable to another file in Python?

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.


1 Answers

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.

like image 185
Adam Rackis Avatar answered Nov 14 '22 23:11

Adam Rackis