简体   繁体   English

如何在多个文件之间共享全局变量?

[英]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:文件 1:

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:文件2:

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?问题是,当我单击按钮时,在 edit() 函数中更新 globalVar,但我在 file2 中的 console.log(globalVar) 它显示 ' '。我的问题是当我单击时如何将 globalVar 传递给 file2按钮?

If you truly want a global variable (not advisable, of course) then you're always 100% free to do如果您真的想要一个全局变量(当然不建议这样做),那么您始终可以 100% 自由地做

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全局变量.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.唯一的风险是,如果您进行代码拆分,webpack 可能会将这个相同的“全局”值复制到多个包中,具体取决于您的设置。 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; webpack 从来没有这样做过; that comment was based on a misunderstanding on my part.该评论是基于我的误解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM