July 1, 2018

How to live-reload a React Native app written in TypeScript

One of React Native’s best features is being able to immediately preview code changes on your device after you save your JavaScript files. While this comes for free when your app is written in vanilla JavaScript, there’s a little bit of configuration to achieve the same using TypeScript.

Live reloads when using the Expo client app

I initially set up my app by following this excellent guide to compile my TypeScript code and run it in the Expo client. I have since ejected to a pure React Native app (see below), but Expo made it super easy to learn the React Native toolset and get the app up and running.

As the guide shows, you add TypeScript support by installing these dependencies:

yarn add concurrently rimraf -D

… and adding a few scripts in package.json:

...
"scripts": {
  "tsc": "tsc",
  "clean": "rimraf build",
  "build": "yarn run clean && yarn run tsc",
  "watch": "yarn run build -w",
  "watchAndStart": "concurrently \"yarn run watch\" \"yarn run start\"",
  "buildAndStart": "yarn run build && yarn run watchAndStart"
}
...

All of the magic happens when you run:

yarn buildAndStart

This tasks kicks off one initial build and then runs watchAndStart, where there are a few key components to make live reloads work:

  • concurrently — This runs the two given commands concurrently. Here we’re simultaneously recompiling TypeScript files whenever they change (yarn run watch), and starting the app in Expo (yarn run start)
  • Yarn will pass the -w flag from yarn run build -w through to yarn run tsc and then eventually to the actual tsc command. This compiler option will watch input files and trigger recompiliation on changes

The Expo client will be watching your TypeScript output folder for changes and will automatically reload the app.

Live reloads when running a pure React Native app on iOS

I recently ejected from Expo so I now have a pure React Native app. You need to use a slightly different set of scripts to get live reloading working.

In package.json:

...
"scripts": {
  "tsc": "tsc",
  "clean": "rimraf build",
  "build": "yarn run clean && yarn run tsc",
  "watch": "yarn run build -w",
  "watchAndRunIos": "concurrently \"yarn run watch\" \"yarn run ios\"",
  "buildAndStartIos": "yarn run build && yarn run watchAndRunIos",
},
...

The iOS Simulator should now load your compiled app, and the tsc command will recompile your code whenever you make changes.

In the iOS simulator you can either hit ⌘R to manually reload the latest JavaScript, or you can enable Live Reload in the Developer Tools menu (⌘D) to reload the app as soon as you press ⌘S in your text editor:

React Native Developer Tools menuReact Native Developer Tools menu

That’s it! Enjoy vastly quicker development cycles!


React Native Expo TypeScript


Next post
Create global Quip shortcuts using Alfred and AppleScript