PWA再入門~React Native(Expo)アプリのPWA化~

下記HPを参考にしました。

Expoで制作したReactNativeアプリをPWA対応Webビルドする必要最小限の手順 #SPA - Qiita

fyi/enabling-web-service-workers.md at master · expo/fyi · GitHub

 

expo customize:web 周辺からやっていきます。

 

ここでは、㋐と違って、㋑に忠実に従ってやってます。

以下、㋑の抜粋です。

Enabling web service workers

 

Start from a template: npx create-react-native-app -t with-workbox・・⓵

Expo's Webpack config has is capable of generating icons, splash screens, manifests, and metadata for your progressive web app based on the app.json and other configuration used for your native app. However, the offline support must be added to your Webpack config manually.

  1. Install the required Workbox dependencies: package.json
  2. Create a local webpack.config.js in your project: expo customize:web
  3. Copy the template webpack.config.js
  4. Create the src/service-worker.js and src/serviceWorkerRegistration.js (the file path is important).
  • Optionally, you can create a noop file for native. ・・②
  1. In your App.js (or other entry file) import the registration and invoke the register method.

①は無視してよいです。下線部のコードからもコピーして取ってこれるからです。

1.では、提供されるpackage.jsonから、コードをコピーし、自分のプロジェクトのpackage.jsonにペーストします。

npx expo install --fixとしておきます。

2. expo customize:webをコマンドプロンプトで実行

3.下線部のwebpack.config.jsをすべてコピーして、自分のプロジェクトのwebpack.config.jsにペースト

4.Expoでは、プロジェクト直下にsrcディレクトリはないので、自分で作成します。その下に、それぞれのファイルをコピー&ペーストで作成します。

②も無視でよいです。

5.下記のようにコードを追記します。③と④。

import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View } from "react-native";

import * as serviceWorkerRegistration from "./src/serviceWorkerRegistration";・・⓷

export default function App() {
  return (
    <View style={styles.container}>
      <Text>Hello!</Text>
      <StatusBar style="auto" />
    </View>
  );
}

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

serviceWorkerRegistration.register();・・・⓸

 

次に、

npx expo install react-native-web react-dom

npx expo install --fix

最近は、コマンドが下記のように変更になってます。

expo build:web ⇒ npx expo export:web

 

ローカルサーバで確認

npx serve web-build --single

 

それでは次に、web-buildディレクトリを、firebase hostingします。

npm install -g firebase-tools

firebase init

firebase.json内の  ”public":"public"を "public":"web-build"に変更

{
  "hosting": {
    "public": "web-build",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"]
  }
}

firebase deploy

 

Deploy complete!と出れば成功です。

 

https://[firebaseのプロジェクト名].web.appのようなURLが出ます。

.comで終わるURLも使用できます。firebaseの方で確認できます。

スマホでこのURLにアクセスすると、ウェブブラウザで表示され、右上の縦3ドットを押して、メニュー表示し、ダウンロードを押すとダウンロード、インストールされ、その後はオフラインでも一部使用可なようです。PCなら、Microsoft Edgeで開き、同様に、右上の縦3ドットから、アプリをインストールすることができます。