Skip to content

Instantly share code, notes, and snippets.

@davidgilbertson
Last active November 9, 2020 03:05
Show Gist options
  • Star 58 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save davidgilbertson/9bee68548037fe00f2a8 to your computer and use it in GitHub Desktop.
Save davidgilbertson/9bee68548037fe00f2a8 to your computer and use it in GitHub Desktop.

First of all, this is not my brilliant effort to get react-native working on Windows, it is the collation of work by others, particularly @mqli and @Bernd Wessels. I've just summarised what worked for me.

If you would prefer to read what I've plagerised, head over to mqli's great gist

Disclaimer

  • The below is tested with react-native-cli 0.1.5, react-native 0.12.0 on Windows 10, node 4.1.1, and Android (physical Nexus 6 and AVD with API v22)
  • I hope this will all be redundant in a few weeks. Please comment on stuff that is now fixed and I will update this to keep it relevant.
  • Sprinkle a bit of YMMV around

Keep this github issue handy, it’s the bucket for all Windows/Linux related tricks to get RN working.

Let's get started...

Install the stuff

The official instructions for getting started and android setup should be followed first. You can skip the parts about installing watchman and flow. Downloading all the android stuff can take up to an hour, so don't get too exceted too soon.

Get Android working first

Before getting into any react-specific things, make sure you can get one of the demo apps from android studio up and running. Then you know any issues you hit are actually react-native issues.

NPM 3 a no-no

Not really Windows-specific, but if you downloaded and installed node 4.1.1 you're probably going to have npm3. Sad trombone. You’re going to have troubles described here so you will need to npm install -g 'npm@<3'. Run npm -v to ensure you've downgraded to 2-something.

From here on in, references to node_modules refer to the contents of that initialised project.

Fix double slash issues with Windows

In node_modules\react-native\packager\react-packager\src\DependencyResolver\index.js add deps = deps.replace(/\\\\/g,'\\'); at the top of defineModuleCode (line 166) as per the mqli gist

Fix hard-coded reference to sh

Then in node_modules\react-native\local-cli\run-packager.js change the contents to

'use strict';

var path = require('path');
var child_process = require('child_process');

module.exports = function(newWindow) {
  if (newWindow) {
    child_process.spawnSync('open', [
      path.resolve(__dirname, '..', 'packager', 'launchPackager.command')
    ]);
  } else {
    child_process.spawn('node', [
      path.resolve(__dirname, '..', 'packager', 'packager.js'),
      '--projectRoots',
      process.cwd(),
    ], {stdio: 'inherit'});
  }
};

as per the above-mentioned gist.

Pro-tip, if you use WebStorm, you can copy some code from the internet, then select the equivalent text in the file in webstorm, right click and pick Compare with clipboard. You'll get a diff of the two snippets.

Start-up script

Change the start command in package.json scripts to read "start": "node node_modules/react-native/packager/packager.js". Again there was a direct reference here to sh. Tsk tsk.

Run-android, run

The official guide says to run react-native run-android. This will package the apk and send it to a device or emulator. I get the impression this is also supposed to start the dev server that bundles the JS. But it don't. So after running react-native run-android you will need to run npm start (which runs the start script you fixed in the previous step).

Debugging

If you're keen to get debugging working (as it is it tries to use an applescript to start Chrome), check out this PR by Spencer Elliott. Read the comments though, it changes package.js which is going to be moved, so as with the above you're making changes that will disappear with the next update.

For a quick and dirty fix, change the getDevToolsLauncher function to the following (in 0.13.0-rc the code is now in node_modules\react-native\packager\getDevToolsMiddleware.js, earlier versions it's in node_modules\react-native\packager\packager.js - the below is a code sample from 0.12.0)

function getDevToolsLauncher(options) {
  var debugRunning = false; // New code

  return function(req, res, next) {
    if (req.url === '/debugger-ui') {
      var debuggerPath = path.join(__dirname, 'debugger.html');
      res.writeHead(200, {'Content-Type': 'text/html'});
      fs.createReadStream(debuggerPath).pipe(res);
    } else if (req.url === '/launch-chrome-devtools') {
      var debuggerURL = 'http://localhost:' + options.port + '/debugger-ui';
      var script = 'launchChromeDevTools.applescript';
      console.log('Launching Dev Tools...');

      debugRunning || require('child_process').exec('start chrome "' + debuggerURL + '"'); // New code
      debugRunning = true; // New code

      //execFile(path.join(__dirname, script), [debuggerURL], function(err, stdout, stderr) {
      //  if (err) {
      //    console.log('Failed to run ' + script, err);
      //  }
      //  console.log(stdout);
      //  console.warn(stderr);
      //});
      res.end('OK');
    } else {
      next();
    }
  };
}

Note the start chrome part, this might be different for you. Whatever you can type into cmd.exe you can use here.

Running on device

If you want to run this on a real device follow the instructions found here. Specifically, run adb reverse tcp:8081 tcp:8081.

Outro

So you've done all this and still getting errors? Yeah, I feel ya. I also had issues with virtualisation. It doesn't seem to be possible to have Hyper-V installed and also run virtualization for Android emulators (prove me wrong, please). And there was another issue with the API version of the emulator, all I can say is play with these, since they don't seem to be Windows-specific, and there are plenty of solved issues in the repo to search.

Bonus

After a few weeks of using React Native I've found these scripts handy for building and deploying. Maybe you'll find them usefull too

  "scripts": {
    "install-dev": "react-native run-android",
    "start": "node node_modules/react-native/packager/packager.js",
    "get-js": "curl \"http://localhost:8081/index.android.bundle?platform=android&dev=false&minify=true\" -o \"android/app/src/main/assets/index.android.bundle\"",
    "assemble": "cd android && gradlew assembleRelease && cd ..",
    "install": "cd android && gradlew installRelease && cd .."
  },
@danhanfry
Copy link

I can not believe it. I still not working.Really I do not understand.

sdk I have everything installed
Android emulator studio 4.1.2
Node: 4.1.1
NPM: 2.14.4

screenshot_1

@abdelouahabb
Copy link

I uploaded the same folders i have, try them
https://drive.google.com/file/d/0B-Iu7VFIRkh4OURZMHUzd1lhTUE/view

@danhanfry
Copy link

screenshot_2
@abdelouahabb many thank you very much. But I regret to tell you that the file you uploaded has a compression failure. using winrar and 7zip

@abdelouahabb
Copy link

I think this is a problem while you downloaded it, here is a screenshot using 7-zip (check the crc if it is the same)
sans titre
sans titre

@danhanfry
Copy link

I apologize, you're right the file is correct.

I'm checking the version. From what I see, in the first attempt to start the server, gives failure. Then early in the following no. but I still have red screen

I'm starting the server node node node_modules/react-native/packager/packager.js It is correct?

screenshot_3

@abdelouahabb
Copy link

BTW, I forgot to give you my configuration about where files are:
The project, and the react-native-cli ,
I have android sdk at the default path:
C:\android-sdk-windows ,
paste react-native-cli folder in node global modules folder :
C:\Users\Your-Name\AppData\Roaming\npm\node_modules
the project, i initialized it at:
C:\Users\Your-name
JDK version is the latest jdk1.8.0_60
Now, get inside the AwesomeProject folder, and run first the server :
react-native start
then, run the command that converts your code to android apk file, and run it on the phone (I used the simulated phone):
react-native run-android
and about your problem, I guess this is about your node.js version, because even this error i just saw, this is because of node, me, I have 4.0.0

@danhanfry
Copy link

thank you. I will install everything you could SDK if I'm missing something and set it as you have it.

If not me, I reinstall the operating system. haha

@absolutelyNoWarranty
Copy link

What to do about watchman (and flow?) which your guide says to ignore?
The server crashes with
ERROR Watcher took too long to load
Try running watchman version from your terminal

@danhanfry
Copy link

Thank you all, he was finally able to react to play-native
Now it would be good to know how to compile the apk for production

https://gist.github.com/marty-wang/5a71e9d0a6a2c6d6263c

I found this great guide but does not work in windows me. If anyone knows anything.

@davidgilbertson
Copy link
Author

@danhanfry congrats! This chap has a pull request for better instructions on generating an apk: https://github.com/satya164/react-native/blob/signed-apk/docs/SignedAPKAndroid.md, I haven't tried it myself though.

@absolutelyNoWarranty, I'm able to develop just fine without watchman and flow. The packager is doing the reloading (FB says "We recommend installing watchman, otherwise you might hit a node file watching bug"). Flow would be nice but not required (it's just type checking); there's a github issue in the flow repo with many many +1s for Windows support.

@absolutelyNoWarranty
Copy link

I'm using node v0.12.2, npm v2.7.4, react-native v0.1.4.

I was able to run the server without a crash by starting it manually with the nonPersistent flag. node node_modules/react-native/packager/packager.js --nonPersistent --skipflow But (obviously) there's no reloading ...

EDIT:
I was able to get live reloading by setting the timeout in node_modules\react-native\packager\react-packager\src\FileWatcher\index.js to a larger number.

@danhanfry
Copy link

@davidgilbertson thanks for the link, I'll see him.

I would like if possible to añadieses your guide adb reverse tcp:8081 tcp:8081 for example, made the difference for me to run.

@BerndWessels
Copy link

If you are using Hyper-V you can use the free Visual Studio Emulator for Android. The standalone download link is at the bottom of that page.

It is very powerful, fast and you don't have to turn off your Hyper-V to use the default Android Emulator.

To use it with react-native you just have to add a key and value to your registry:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Android SDK Tools

String Value:
Name: Path
Value: C:\Program Files\Android\sdk

Obviously the path value might be different on your machine.

This emulator also need the adb reverse tcp:8081 tcp:8081 command executed once before starting.

Then restart the emulator and when it is running you can just do react-native run-android as usual.

visual studio emulator regedit

@rt012
Copy link

rt012 commented Oct 6, 2015

It works!! @davidgilbertson Thank you for this good explanation!! Is there someone who already gets the UIExplorer Example to work on android? Is there something I´ve to consider? When I´m calling "react-native run-android" in the UIExplorer-Direcotory I get the Message: "Comand 'run-android' unrecognized. Did you mean to run this inside a react-native project?"

@flyher
Copy link

flyher commented Oct 10, 2015

@danhanfry
hi,it seems that the same problem happened to me.
red screen,i try all functions how many i found,but it didn't work!

@danhanfry
Copy link

flyher I finally I formatted the windows
and it works for me.

However he left the version 0.12 anyone tried?

@agamm
Copy link

agamm commented Jan 4, 2016

This might help someone: https://gist.github.com/funerr/5b645642323eae252c41
It runs the react native project automatically.

@jerkovicl
Copy link

JS fiddle for React Native : https://rnplay.org/

@apooslr
Copy link

apooslr commented May 12, 2017

I dont have either of the files:
node_modules\react-native\packager\react-packager\src\DependencyResolver\index.js
node_modules\react-native\local-cli\run-packager.js

what do I do ??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment