LoginSignup
6
1

More than 3 years have passed since last update.

React Nativeでエントリーポイントを変更する

Last updated at Posted at 2019-12-31

expo-cliで作成したReactNativeアプリでエントリーポイントの設定をしようとしたところ少し手こずったので備忘として残したいと思います。

エントリーポイント初期設定

expo-cliで生成したReact Nativeプロジェクト(TypeScript)のディレクトリ構成は以下のようになっています。

my-rn-app
├── App.tsx
├── app.json
├── assets
├── babel.config.js
├── node_modules
├── package-lock.json
├── package.json
└── tsconfig.json

エントリーポイント指定

ルートディレクトリにApp.tsxがあるのが自分的に嫌だったので、srcディレクトリを作りその配下にApp.tsxを移動させました。

my-rn-app
├── src
│    └── App.tsx
├── app.json
├── assets
├── babel.config.js
├── node_modules
├── package-lock.json
├── package.json
└── tsconfig.json

するとエミュレータ上で以下のようなエラーが発生しました。
スクリーンショット 2019-12-31 16.22.13.png

このエラー内容から、エントリーポイントの設定はnode_module/expo/AppEntry.jsで行なっていると推測できました。

ではエントリーポイントを指定している箇所はどこでしょうか?
探してみると、エントリーポイント:node_module/expo/AppEntry.jspackage.jsonnameプロパティで指定していました。

"main": "node_modules/expo/AppEntry.js",

この部分をsrc/App.tsxに変更します。

"main": "src/App.tsx",

変更後、エミュレータでアプリが正常に起動するか確認すると、

スクリーンショット 2019-12-31 16.35.39.png

エラーがでてました。
どうやらアプリを実行するためのエントリーポイントの登録を行う必要があるようです。

エントリーポイント登録

公式ドキュメントには以下のような説明がありました。

App root components should register themselves with AppRegistry.registerComponent, then the native system can load the bundle for the app and then actually run the app when it's ready by invoking AppRegistry.runApplication.

アプリのルートコンポーネントはAppRegistry.registerComponentに登録する必要があります。ネイティブシステムはアプリのバンドルをロードし、AppRegistry.runApplicationを呼び出して準備ができたら実際にアプリを実行できます。

とのことなので、src/App.tsxAppRegistry.registerComponentでルートコンポーネントを登録、したいところですがregisterComopnentの記載を確認すると

static registerComponent(appKey, componentProvider, section?)

第一引数にappKeyというものが必要になります。
調べると、appKeyapp.jsonに設定するものだそうなので、プロパティを追加します。

app.json

{
  "expo": {
    "appKey": <APP_KEY>,

  }
}

ここまでできたら残すはsrc/App.tsxにAppRegistry.registerComponentでルートコンポーネントを登録するのみです。

src/App.tsx

import React from 'react';
import { StyleSheet, Text, View, AppRegistry } from 'react-native';
import { expo } from './../app.json';
export default function App() {
  return (
    <View style={styles.container}>
      <Text>Open up App.tsx to start working on your app!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center'
  }
});

AppRegistry.registerComponent(expo.appKey, () => App);

エミュレータでアプリを確認すると正常に動作することが確認できましました。

スクリーンショット 2019-12-31 16.55.04.png

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1