Home

Globals In React Native

July 15, 2016

Recently I ran into a problem in React Native.

I wanted to be able to have more granular control of my build besides React Native's __DEV__.

Our QA people need to have a few tools at their disposal to run the APP vs our live and test servers. I don't want to make them download the project on Github and run it. That would force them onto a mac for iOS builds. I don't want to ship the app with __DEV__ on. It would be quite complex to have them connect to some dev package server to run the app A third option was needed. There should be a __QA__ flag. This way I can release the APP in without __DEV__ but keep some QA features I want. The naive way would be to have something like a globals.js file that you include and edit the file for different releases. eg.

//for production release
GLOBAL.__QA__ = false;
GLOBAL.__PROD__ = true;

But the one thing I don't want to do is EVER edit code manually for different releases. It should all be handled on the command line with make

I wish react-native had some easy way to define globals from the command line. like the C preproccessor defines eg.

#ifdef SOME_FLAG
...
#endif

and then you can switch your flags on and off from command line with gcc file.cpp -D SOME_FLAG=1

As side note I make use of defines in my AppDelegate.m so I don't have to comment out code for production or release.

#if defined(DEBUG)
  jsCodeLocation = [NSURL URLWithString:@"http://127.0.0.1:8081/index.ios.bundle?platform=ios&dev=true"];
#else
  /**
   * OPTION 2
   * Load from pre-bundled file on disk. The static bundle is automatically
   * generated by "Bundle React Native code and images" build step.
   */

  jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif

So the problem is:

I want to have flags for the code without manually having to edit files for releases.

I came up with a solution I am okay with for right now.

I start with a globals.js file and include that in my index.ios.js and index.android.js files.

Then I made files for each of the different enviroments I wanted to support. globals_dev.js globals_qa.js globals_prod.js

All with the 2 flags I want in correctly set eg for globals_qa.js

GLOBAL.__QA__ = true;
GLOBAL.__PROD__ = false;

Then when I go to create a build for anything I concat the correct globals_x.js into globals.js to set all the flags to the values I wanted.

It looks something like this.

cat globals_x.js > globals.js

So my Makefile instruction for qa might look something like this. (remember I want QA to be a production build with 1 flag set)

(I also made custom builder and uploader scripts for iOS but ill save that for a later post)

QA:
  cat globals_dev.js > globals.js
  cd android && ./gradlew assembleRelease
  ./scripts/build_ios.sh

BOOM now with this you can setup any enviroment you want with as many flags as you want to support!