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
このエラー内容から、エントリーポイントの設定はnode_module/expo/AppEntry.jsで行なっていると推測できました。
ではエントリーポイントを指定している箇所はどこでしょうか?
探してみると、エントリーポイント:node_module/expo/AppEntry.jsはpackage.jsonのnameプロパティで指定していました。
"main": "node_modules/expo/AppEntry.js",
この部分をsrc/App.tsxに変更します。
"main": "src/App.tsx",
変更後、エミュレータでアプリが正常に起動するか確認すると、
エラーがでてました。
どうやらアプリを実行するためのエントリーポイントの登録を行う必要があるようです。
エントリーポイント登録
公式ドキュメントには以下のような説明がありました。
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.tsxのAppRegistry.registerComponentでルートコンポーネントを登録、したいところですがregisterComopnentの記載を確認すると
static registerComponent(appKey, componentProvider, section?)
第一引数にappKeyというものが必要になります。
調べると、appKeyはapp.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);
エミュレータでアプリを確認すると正常に動作することが確認できましました。
