简体   繁体   English

我在哪里以及如何在reactjs应用程序中指定全局变量

[英]where and how can I specify global vars in a reactjs app

I want to define some global imports or vars to use them in all my files. 我想定义一些全局导入或变量,以在我的所有文件中使用它们。

an example would be this 一个例子就是

var T = require('react-redux-i18n').Translate;

at the moment I have to do this in all of my files. 目前,我必须在所有文件中执行此操作。 Is there a way to do this only once in the index.js? 有没有办法在index.js中仅执行一次?

Thanks 谢谢

why not do it the classic javascript way with module.exports? 为什么不使用module.exports的经典javascript方式呢? ie in index.js do somthing like 即在index.js中做类似

var1 = '..';
var2 = '...';
...
module.exports= {var1, var2}

then in other files just do 然后在其他文件中

import /path/to/index
...
console.log(index.var1)
console.log(index.var2)

or to import only what you need do 或仅导入您需要的内容

import {name_of_var_i_need} from /path/to/index
...

although I would suggest doing this in a constants.js file or something like that instead of having them all in your index.js (unless of course they need to be initialize in index) 尽管我建议在constants.js文件或类似的文件中执行此操作,而不是将它们全部包含在index.js中(除非它们需要在索引中初始化)

Technically you can put any globals on the window object and then read from it. 从技术上讲,您可以将任何全局变量放在window对象上,然后从中读取。 This is generally considered a bad practice because it's confusing and doesn't work with optimization techniques like code splitting. 通常认为这是一种不好的做法,因为它会造成混淆,并且无法与代码拆分等优化技术配合使用。

My advice: don't try to save keystrokes like this. 我的建议:不要尝试保存这样的按键。 Copying a few imports to every file you use them in is not a big deal, and makes program easy to understand both for you and for different tools. 将几个导入复制到您使用它们的每个文件中并不是什么大问题,并且可以使您和您的不同工具都易于理解程序。 You can hack around it but in the end it won't be worth it. 您可以破解它,但最终它不值得。

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

相关问题 我应该在哪里从Reactjs应用程序中获取数据? - Where should I fetch data in Reactjs app? 如何在Reactjs应用程序上安装LESS css? - How can i install LESS css on Reactjs App? 在reactjs应用程序中,如何获得正确的dom元素宽度? - In reactjs app, how can I get the right width of a dom element? 如何在我的 ReactJS 应用程序中添加倒数计时器 - How can I add Countdown Timer in my ReactJS app 我的 Reactjs 应用程序中是否需要全局 state? - Do I need a global state in my Reactjs app? 我可以将ReactJS Native中的值分配给Swift全局变量吗? 如果是这样,怎么办? - Can I assign a value from ReactJS Native to a Swift global variable? If so, how? 在函数中使用动态导入时,如何在全局变量中指定类型信息? - When using dynamic import in a function, how can I specify type info in global variable? 如何在 create-react-app 中指定全局类型声明? - How to specify global type declarations in create-react-app? 我可以在 reactjs 的类之外声明一个全局变量吗 - can i declare a global variable outside the class in reactjs 我可以在不将其作为参数传递的情况下,使一个全局函数访问另一全局函数的局部变量吗? - Can I give one global function access to another global function's local vars, without passing them as parameters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM