Sharing Codes between React Web App and React Native (Expo) App
2 min readDec 20, 2020
Prerequisites
- React
- React Native
- Expo/Expo Cli
- Async and Promises
- Node
- Typescript
- vtecx
Section
- Creating a simple web app using vtecx
- Creating a native app using expo
- Sharing codes from web app to native app
Create a simple web app using vtecx
- At the root of the app
npm install create-vtecx-app [your-web-app] eg: web-app (Fig 1)
cd [your-web-app]
npm install
npm run login
Create a simple native app using expo
expo init [your-expo-app]
cd [your-expo-app] eg: expo-app (Fig 1)
rm -rf .git
- Simply delete .git folder inside the expo app if your app already includes a .git at the root
- We are going to share the codes from the web app to the native app (not the other way around)
- We need to deal with three files mostly
metro.config.js
babel.config.js
tsconfig.js
Sharing codes from web app to native app
Metro Configuration
When we use the expo start command, the expo-cli uses the metro configuration to bundle for android and iOS platforms
Proxy and Reflect
Before we go through the configuration, we need to know what proxy and reflect is. It would be clear if we go through an example
- Create a simple object with two properties/attributes.
- Create a new Proxy
- Proxy requires a target [which is the person obj] and a handler
- Handler methods (we will be focussing get only) other methods can be found in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy
- Add a custom get in handler
- In get we can define custom attribute, which is
sir
, it will just add aSir,
string before the person.name if we type inconsole.log(person.sir)
- Reflect is a global static class.
- Reflect.get expects a target and prop name which we passed using the arguments
Now lets get back to metro.config.js
- First we need to add a transformer property with getTransformOptions, it will help us to import json files from another directory
- Then we will add a resolver, we need add extraNodeModules with a proxy.
- Main purpose of the extraNodeModules is to identify where to import from
- If the import has
@web
then it will import functions/components from web-folder - If there is an import (eg: lodash) from vendor then it will import from the expo-app node_modules directory
- We are also adding a watchFolders option so that the expo updates, if we update the code in the web app directory
- For more details go to https://facebook.github.io/metro/docs/configuration
Babel Configuration
- Now the transpiler needs to understand how the deal with the
@web
import and we have defined module alias for it.
Typescript Configuration
- Typescript also needs to know how
@web
import would be dealt with
Create a utilities folder inside the src folder and then create a simple adder function (Inside the web app directory)
Inside the expo app
Thanks