如何在多个文件之间共享全局变量? [英] How do I share a global variable between multiple files?

查看:207
本文介绍了如何在多个文件之间共享全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个都需要全局变量的文件.我有一个点击按钮.单击后,运行一个函数.代码如下:

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:

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

文件2:

var globalVar = require(./file1);

function openModal(){

if (globarVar != ''){
 do something

} }

问题是当我单击按钮时,globalVar在edit()函数中更新,但是我在file2中的console.log(globalVar)显示为''.我的问题是当出现以下情况时如何将globalVar传递给file2我点击按钮了吗?

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?

推荐答案

如果您确实想要全局变量(当然不建议这样做),那么您总是100%可以自由使用

If you truly want a global variable (not advisable, of course) then you're always 100% free to do

window.globalVar = 0;

在您的任何模块中.

当然,更健壮的解决方案是将该全局变量置于某种专用模块中,例如

The more robust solution would of course be to have this global variable sit in some sort of dedicated module, like

globalVar.js

globalVar.js

export default {
    value: 0
};

然后您就可以

import globalVal from './globalVar';

globalVal.value = 'whatever';

来自任何需要的模块.

from any modules needed.

唯一的风险是,如果您要进行代码拆分,则Webpack可能会将相同的全局"值复制到多个包中,具体取决于您的设置.因此,单独的模块将使用此本地变量的本地副本. 编辑-这不是事实. webpack从未这样做过;该评论是基于我的误解.

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.

这篇关于如何在多个文件之间共享全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆