RN Micro – How to create an app loading metro server?

Create a JS project

  • Create a JS project as below
// package.json
{
  "name": "example",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "reset": "rm yarn.lock; rm -rf node_modules; yarn install; watchman watch-del-all; rm -rf /tmp/metro-*; yarn start --reset-cache",
    "start": "yarn react-native start",
    "restart": "yarn install; watchman watch-del-all; yarn start --reset-cache"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-native": "^0.73.6"
  },
  "devDependencies": {
    "@react-native/metro-config": "^0.75.0-main",
    "@types/react": "^18.2.79",
    "@types/react-native": "^0.73.0",
    "typescript": "^5.4.5"
  }
}
// metro.config.js

const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');

/**
 * Metro configuration
 * https://facebook.github.io/metro/docs/configuration
 *
 * @type {import('metro-config').MetroConfig}
 */
const config = {};

module.exports = mergeConfig(getDefaultConfig(__dirname), config);
// index.tsx

import React from 'react';
import {
  AppRegistry,
  ...
} from 'react-native';

const HelloWorld = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.hello}>Hello, World</Text>
    </View>
  );
};

AppRegistry.registerComponent(
  'MyReactNativeApp', // this name is needed to be the same with the one in native Android and iOS
  () => HelloWorld
);
  • Run the project
$ yarn install
$ yarn start

Create a native Android project

How to load a pre-bundled file?

  • Pre-bundle RN file
  "scripts": {
    ...
    "build-android": "react-native bundle --platform android --dev false --entry-file index.tsx --bundle-output /Volumes/Data/New/sdk/react-native-new-android/android/app/src/main/assets/index.android.bundle --assets-dest /Volumes/Data/New/sdk/react-native-new-android/android/app/src/main/res"
  },
  • Copy “index.android.bundle” into emulator’s “data\data\xxxx” folder
  • Change Android codes
    private final ReactNativeHost mReactNativeHost =
            new DefaultReactNativeHost(this) {
                ...
                @Override
                protected String getJSBundleFile() {
                    // Return the file path where your bundle is located
                    if (BuildConfig.DEBUG) {
                        return "http://localhost:8081/index.android.bundle";
                    } else {
                        return new File(getApplication().getFilesDir(), "index.android.bundle").getAbsolutePath();
                    }
                }

                @Override
                protected ReactInstanceManager createReactInstanceManager() {
                    return super.createReactInstanceManager();
                }
                ...

Create a native iOS project

Be the first to comment

Leave a Reply

Your email address will not be published.


*