react-nativeでローカルで作成したパッケージを組み込む
パッケージを部品化して管理したい
基本的には1つのプロジェクトで管理してもよいですが、開発の過程で部品化してあわよくば 公開したいとか・・・
やり方
ざっくりいうとこんな感じ
- パッケージ名を決める
- ディレクトリを作成する
yarn init
またはnpm init
する- コードを実装する
- サンプルプロジェクトに入れたりして実験する
- あわよくば公開する(今回はしない)
手順
サンプルプロジェクトを作成する
npx react-native init sampleDemo01 --template react-native-template-typescript
ローカルパッケージのディレクトリを作成する
mkdir react-native-helloworld
yarn initする
cd react-native-helloworld yarn init
↓
{ "name": "react-native-helloworld", "version": "0.0.1", "description": "demo", "main": "index.js", "author": "mshige1979", "license": "MIT", "peerDependencies": { "react": "*", "react-native": "*" } }
※peerDependenciesの部分は必要になるので追加
index.jsにコンポーネントを実装
index.js
import React from "react"; import { View, Text } from "react-native"; const Helloworld = (props) => { return ( <View> <Text>Hello, {props.message}</Text> </View> ); }; export default Helloworld;
サンプルプロジェクトへローカルインストール
cd ../sampleDemo01 yarn add ../react-native-helloworld
※パッケージのディレクトリを指定することでインストール可能 ※修正したら再度、インストール処理を行わないと反映されない
サンプルプロジェクトへ実装
sampleDemo01/App.tsx
import React from 'react'; import {SafeAreaView} from 'react-native'; import Helloworld from 'react-native-helloworld'; function App(): JSX.Element { return ( <SafeAreaView> <Helloworld message={'hogehoge'} /> </SafeAreaView> ); } export default App;
確認
こんな感じ Typescriptで対応する場合は型定義とか必要かと 上のやつでは見えないけどVSCodeでワーニング出ます
参考
所感
アプリ作ってみようかな・・・ 管理多少めんどうだけど