简体   繁体   中英

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?

Thanks

why not do it the classic javascript way with module.exports? ie in index.js do somthing like

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)

Technically you can put any globals on the window object and then read from it. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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