[英]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.