It is common situation that we would like to define some global functions in any projects.
Without global function, we should write import
statement every time.
But is this against react philosophy? Don't worry, I found the following code in the real world project.
// make the i18n function "t" global so we don't have to import it in basically every file
import { t, jt } from "c-3po";
global.t = t;
global.jt = jt;
I defined a global function _
(lodash) in current React Native project and I don't have any problems.
How to
Very easy.
Write this in your bootstrap file (e.g. app.js
)
import _ from 'lodash'
global._ = _
Then you can use _
everywhere without import
explicitly.
<Text style={styles.title}>
{_.truncate(someText, { length: 22 })}
</Text>
Tell ESLint
ESLint will regard global function as error. So let's add the following config to .eslintrc
:
{
//...
"globals": {
"_": false
},
//...
}
Note that a lot of global functions might cause readability, dependency and testability problems.
Top comments (0)