LoginSignup
10
3

More than 5 years have passed since last update.

📱Reason + React NativeでiOSアプリを作る

Last updated at Posted at 2017-12-09

過去に遡ってReason ML Advent Calendarの3日目を書く。

今回は、ReasonとReact Nativeを組合せてiOSアプリを書く。

:camera: 完成図とソースコード

Screen Shot 2017-12-09 at 22.50.01.png

:coffee: React Nativeのセットアップ

ここは普通のReact Nativeプロジェクトと違いはないはず。

create-react-native-appを使うと一瞬で完成した。 しかし、一瞬すぎて何も分かならかったので、個別にパッケージをいれていく。

プロジェクトの初期化

# 名前などを決める
$ npm init

# 依存するライブラリをいれる。
$ yarn add react-native react

エントリポイント

index.js で起点となるコンポンーネントを起く。


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

export default class App extends Component {
  render() {
    return (
      <Text>Hello world!</Text>
    );
  }
}

AppRegistry.registerComponent('AwesomeProject', () => App);

設定ファイル

app.json でプロジェクト名を設定する。

{
  "name": "AwesomeProject",
  "displayName": "AwesomeProject"
}

実行

Android/iOSのプロジェクトを生成する。

$ yarn run react-native eject

シミュレータを起動する。

$ yarn run react-native run-ios

:camel: Reasonの導入

bs-react-nativeheを使って、JavaScript部分をReasonに置き換えていく。

インストール

BuckleScriptとReact Nativeのバインディングを追加する。

$ yarn add bs-platform bs-react-native

設定ファイル

Reason/BuckleScriptの設定ファイルである bsconfig.json を作成する。

{
    "name": "my-awesome-app",
    "reason": {
        "react-jsx": 2
    },
    "bsc-flags": ["-bs-super-errors"],
    "bs-dependencies": ["bs-react-native", "reason-react"],
    "sources": [{
        "dir": "re"
    }],
    "refmt": 3
}

コンポーネント

re/app.re にReasonでコンポーネントを記述する。ReasonではJSXが利用できるので、見た目がだいぶJavaScriptというかHTMLに近くなる。

open ReactNative;

let app = () =>
  <View style=Style.(style([flex(1.), justifyContent(`center), alignItems(`center)]))>
    <Text value="Reason is awesome!" />
  </View>;

ビルド

Reasonのビルドはbsbで行なう。

$ yarn run bsb

エントリポイントの書き換え

Reason/BuckleScriptのビルド結果は lib 以下に出力される。 これをエントリポイントから読み込んで利用する。

import { app } from "./lib/js/re/app.js";
import { AppRegistry } from 'react-native';

AppRegistry.registerComponent('AwesomeProject', () => app);

実行

これは先ほどと変わりはない。

$ yarn run react-native run-ios 

:books: 参考資料

:heartbeat: 雑感

  • Docker内で動作させようとして無駄に苦労した。 素直にmacOS上で直接動かしたほうがよかった。
  • 型のサポートを受けつつiOSアプリを書きたいならSwiftという選択肢があるのでは???
10
3
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
10
3