簡體   English   中英

帶有 Create-react-app 的 Cordova

[英]Cordova with Create-react-app

我使用create-react-app創建了一個 ReactJs 應用程序,然后使用npm run build進行了生產npm run build 在我用 Cordova 創建的www文件夾中,我只是從create-react-app 的構建文件夾中復制所有文件,這很好。

我想知道如何與 Cordova 的事件掛鈎,例如:

function startApp() {
  // your app logic
}
if (window.cordova) {
  document.addEventListener('deviceready', startApp, false);
} else {
  startApp();
}

例如,我想在startApp()調用縮小的 JS 文件。 或者是否有任何其他工作流程可用於使 Cordova 事件與 react 應用程序一起使用。

一個小例子會有所幫助。

是否可以完全使用構建文件並直接在 Cordova 中使用 React App? 鑒於有將 ES6 代碼轉換為 ES5 和所有代碼的 Webpack 設置,我不確定這將如何工作。

我是 Cordova 的新手,正在努力解決這個集成方面的問題。

我發現可以讓這兩個工作,並將在這里發布給其他尋找相同的人。 也許還有其他方法可以做到這一點,但這對我有用。

所以基本上我們將使用(說)創建一個 Cordova 應用程序:cordova create testapp com.test.testapp testapp 這會給我一個文件夾結構,如下所示:

testapp
        --hooks
        --platforms
        --plugins
        --www
        --config.xml

現在在 testapp 文件夾中我們運行: create-react-app testappReact 這將在 testapp 文件夾中添加我的反應應用程序。 您的 React 應用程序將在 /src 目錄中有一個主要的 index.js。

我 index.js 確保將您的主要邏輯包裝在一個函數中,然后像這樣調用該函數和 Cordova 對象:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';


const startApp = () => {
ReactDOM.render(
  <App />,
  document.getElementById('root')
);
}

if(!window.cordova) {
  startApp()
} else {
  document.addEventListener('deviceready', startApp, false)
}

現在應該這樣做了,您的應用程序將擁有 Cordova 實例以及您的應用程序內的 navigator.camera 等設備對象。

同樣在您的反應應用程序 index.html 中,它可以在公共文件夾中找到,從您將在 Codova www 文件夾中找到的 index.html 中復制 html。 現在我們可以刪除 www 文件夾中的所有文件。 我們稍后將手動或通過腳本將所有文件從 react apps build 文件夾復制到 Cordova www 文件夾。

所以我的 index.html 看起來像下面這樣,注意作為腳本包含的 cordova.js 文件。

<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>

<head>
    <!--
        Customize this policy to fit your own app's needs. For more guidance, see:
            https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
        Some notes:
            * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
            * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
            * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
                * Enable inline JS: add 'unsafe-inline' to default-src
        -->
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src * data: content:;">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

    <!-- Latest compiled and minified CSS -->
    <title>React App</title>
</head>

<body>
    <div id="root"></div>
   <script type="text/javascript" src="cordova.js"></script>
</body>

</html>

最后在你的 React 應用程序的 package.json 中添加以下行: .... "homepage": "../www" .... 這將確保你的最終構建文件指向正確的路徑。 我們還可以在 package.json 構建腳本中添加以下幾行。

  "scripts": {
    "start": "react-scripts start",
    ***"build": "react-scripts build && robocopy .\\build ..\\www /MIR",***
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "deploy": "npm run build&&gh-pages -d build"
  }

它可以是基於操作系統(Windows/Linux 等)的 robocopy 或 cp-r。

我們應該准備好使用cordova build android/ios構建我們的Cordova應用程序。

我解決了這個問題。 以下是我為尋找解決方案的人提供的分步格式:

  1. Cordova應用程序目錄中復制/創建一個新的React項目(使用create-react-app )。
  2. 清除Cordova應用程序www文件夾中的所有內容。
  3. cd到 React 項目文件夾(您剛剛復制/創建)並打開package.json
  4. dependencies項之前添加"homepage": "./", & 內部腳本將build更改為"build": "react-scripts build && robocopy .\\\\build ..\\\\www /MIR",
  5. 在相同的( React的)目錄中執行npm run build並返回父( Cordova )文件夾,然后在所需的平台上buildemulate您的項目。
  6. 額外提示:如果您在項目中使用<Router>將其更改為<HashRouter>否則您將看到空白顯示,因為屏幕上不會呈現任何內容。

我認為很難找到如何解決這個問題的完整指南。 我是這樣解決的,從頭到尾,以便能夠在 Windows 上的模擬 Android 設備上運行 Create React App:

首先創建一個 React 應用程序或使用您現有的應用程序。

npx create-react-app my-app

https://github.com/facebook/create-react-app#creating-an-app

然后安裝科爾多瓦:

npm install -g cordova

https://cordova.apache.org/docs/en/latest/guide/cli/

在我的例子中,在my-app文件夾中創建一個新的cordova應用程序:

cordova create hello com.example.hello HelloWorld

將目錄更改為hello或您所說的 Cordova 應用程序。

cordova platform add ios
cordova platform add android

運行cordova requirements以查看構建項目所需的內容。

在此處輸入圖片說明

因為我使用的是 Windows,所以在這個例子中我只會為 Android 構建它。

cordova platform remove ios

並確認我只有帶有cordova platform ls Android cordova platform ls

在此處輸入圖片說明

根據cordova requirements命令安裝你需要的東西。 因為我是全新安裝的,所以我需要一切:Java 開發工具包 (JDK) 8、Gradle 和 Android SDK。 鏈接可以在這里找到:

https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html#requirements-and-support

或者:

https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html

https://gradle.org/install/

https://developer.android.com/studio/index.html

安裝后打開Android Studio。 我選擇了標准安裝,但失敗並顯示以下警告:

無法安裝英特爾 HAXM。 詳情請查看安裝日志:“C:\\Users\\Oscar\\AppData\\Local\\Temp\\haxm_log.txt” Intel® HAXM 安裝失敗。 要安裝英特爾® HAXM,請按照以下說明安裝: https ://software.intel.com/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows 安裝程序日志位於

C:\\Users\\Oscar\\AppData\\Local\\Temp\\haxm_log.txt 安裝程序日志內容: === Logging started: 2020-07-10 16:39:27 === 這台計算機不支持 Intel Virtualization Technology (VT- x) 或者它專門由 Hyper-V 使用。 無法安裝 HAXM。 請確保在 Windows 功能中禁用 Hyper-V,或參閱英特爾 HAXM 文檔了解更多信息。

然而,我無論如何都可以啟動應用程序並添加在配置下找到的 Android 虛擬設備 (AVD)。

在此處輸入圖片說明

我選擇添加帶有R系統映像的Pixel XL

但是再次運行cordova requirements ,我可以看到我需要一個API級別為28的Android目標。R是30級。

在此處輸入圖片說明

因此,我安裝了 API 級別為 28 x86_64 的Pie並創建了一個新的虛擬設備。

在此處輸入圖片說明

我沒有打開AVD Manager而是打開了SDK manager ,還下載了 Android 9.0 Pie SDK。

在此處輸入圖片說明

現在一切看起來都不錯:

在此處輸入圖片說明

然后運行cordova emulate android來測試默認的Cordova 應用程序。

如果它有效,它應該是這樣的:

在此處輸入圖片說明

將目錄更改為my-app

編輯package.json並在依賴項之前添加"homepage": "./",

在此處輸入圖片說明

感謝@BlackBeard。 來源: https : //stackoverflow.com/a/46785362/3850405

運行npm run build

清除my-app\\hello\\www所有內容,然后將my-app\\build所有內容復制到my-app\\hello\\www

瞧:

在此處輸入圖片說明

如果不編輯my-app package.json並添加"homepage": "./",它將如下所示:

在此處輸入圖片說明

得到教訓:

1.

如果您在項目中使用<Router>將其更改為<HashRouter>否則您將看到空白顯示,因為屏幕上不會呈現任何內容。 適用於 iOS 和 Android。

來源: https : //stackoverflow.com/a/46785362/3850405

2.

您需要一個白名單來允許 URL。 從文檔:

默認情況下,只允許導航到 file:// URL。 要允許其他 URL,您必須在 config.xml 中添加標簽:

https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/

像這樣安裝:

cordova plugin add cordova-plugin-whitelist

然后編輯位於應用程序根目錄中的config.xml並添加以下任何內容:

<!-- Allow links to example.com -->
<allow-navigation href="http://example.com/*" />

<!-- Wildcards are allowed for the protocol, as a prefix
     to the host, or as a suffix to the path -->
<allow-navigation href="*://*.example.com/*" />

<!-- A wildcard can be used to whitelist the entire network,
     over HTTP and HTTPS.
     *NOT RECOMMENDED* -->
<allow-navigation href="*" />

來源: https : //stackoverflow.com/a/30327204/3850405

3.

即使您使用的是白名單,您可能仍然需要訪問不支持 https 的 http API。 默認情況下,這是不允許的,可能會導致一些真正的頭痛。 也可以通過編輯config.xml並在<platform name="android">下添加以下內容來解決此問題:

<edit-config xmlns:android="http://schemas.android.com/apk/res/android"  file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">     <application android:usesCleartextTraffic="true" /></edit-config>

鑒於您沒有瀏覽到 URL,任何 API 調用都必須指定實際服務器。 我通常使用 Axios,所以我們只需要將我們的服務器添加到默認 URL。 例子:

import axios, { AxiosPromise, AxiosRequestConfig, Method } from 'axios';

const getConfig = (url: string, method: Method, params?: any, data?: any) => {
     const config: AxiosRequestConfig = {
         url: 'http://192.168.1.249' + url,
         method: method,
         responseType: 'json',
         params: params,
         data: data,
         headers: { 'X-Requested-With': 'XMLHttpRequest' },
    }
    return config;
}

export const sendRequest = (url: string, method: Method, params?: any, data?: any): AxiosPromise<any> => {
    return axios(getConfig(url, method))
}

然后像這樣調用:

const path = '/api/test/'

export const initialLoad = (number: number): AxiosPromise<InitialLoadDto> => {
    return sendRequest(path + 'InitialLoad/' + number, 'get');
}

npm i -g react.cordova

https://www.npmjs.com/package/react.cordova

cli 為您完成所有工作。 它已經被修復,現在工作得很好。

*我寫了這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM