Felix
Felix

Reputation: 5619

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

Upvotes: 1

Views: 75

Answers (2)

Dan Abramov
Dan Abramov

Reputation: 268215

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.

Upvotes: 2

Daniel Persaud
Daniel Persaud

Reputation: 104

why not do it the classic javascript way with module.exports? i.e. 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)

Upvotes: 2

Related Questions