23 July 2019

Create React Native App using TypeScript compiled with Babel

Here's every step to creating a React Native app, written in and type checked with TypeScript, but compiled with Babel 7.

You're assumed to have some proficiency with using the terminal.

Tools to Install on your PC

I'm on a Mac, but the steps shouldn't be much different on Ubuntu Linux or Windows.
  1. Install Homebrew.
    It's a package manager for Macs, and Linux too, but if you're on Ubuntu or Debian, I suggest just use the built-in one like APT.
  2. Install Node thru brew.
    Installing Node should include the NPM package manager with it, which is needed below.
  3. Some say to next install Yarn thru brew.
    Yarn is yet another node package manager... you can skip this if you want, it's not strictly needed, and I won't use Yarn in this tutorial.
  4. Fix NPM if you installed Yarn.
    I actually mentioned Yarn at all only because with Homebrew, you might now need to fix the Node NPM install as it might be broken by installing yarn.  Simply[1] run: yarn global add npm.  Remember, we don't need Yarn in this tutorial though.
  5. Install React Native CLI thru npm:npm install -g react-native-cli
    This is basically a template that creates a RN project for you to start from.
[1] https://stackoverflow.com/questions/33870520/npm-install-cannot-find-module-semver/49422151#49422151

New Project with React Native

1. Create a React Native project:
$ react-native init CoolProject

1.5. Upgrade core-js:
I got an error like this:
warning react-native > create-react-class > fbjs > core-js@1.2.7: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.

You just need to upgrade core-js.  Go into your CoolProject folder and run:
npm install --save core-js@^3

2. cd CoolProject to go into the new project's root directory, then install Babel:
$ npm install --save-dev @babel/core @babel/cli
I assume this will install for you Babel 7 or above.  We'll need it later to migrate to TypeScript.

3. Create a lib folder in the project root.
$ mkdir lib
The lib folder will be used to contain the App's JavaScript files. Traditionally, the folder would be called "src", but looking forward, these JavaScript files eventually will be produced by the TypeScript compiler for us.

So instead, we're going to reserve "src" for later when we migrate to TypeScript, instead of calling it "src" right now when we're still dealing with just JavaScript JS, or JSX, files.

Separating the TypeScript and the compiled JavaScript files is a technique to avoid in-source builds (a usual technique used in compiled languages like C++: see e.g. in-source vs out-of-source builds).