【问题标题】:Cordova with Create-react-app带有 Create-react-app 的 Cordova
【发布时间】:2017-09-06 07:25:20
【问题描述】:

我使用 create-react-app 创建了一个 ReactJs 应用程序,然后使用 npm run build 进行了生产构建。在我用 Cordova 创建的 www 文件夹中,我只需从 create-react-app's 构建文件夹中复制所有文件就可以了。

我想知道如何联系 Cordova 的事件,例如:

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

比如我想调用startApp()里面的缩小JS文件。或者是否有任何其他工作流程可用于使 Cordova 事件与反应应用程序一起使用。

一个小例子会很有帮助。

是否可以完全使用构建文件并直接在 Cordova 中使用 React 应用程序?我不确定这将如何工作,因为存在将 ES6 代码转换为 ES5 和所有代码的 Webpack 设置。

我是 Cordova 的新手,正在努力解决这个集成方面的问题。

【问题讨论】:

  • 我已经弄清楚了如何使这两个工作,并将在此处发布给其他寻找相同答案的人。这很简单,也许还有其他方法,但这对我来说非常好。

标签: javascript reactjs cordova create-react-app


【解决方案1】:

我已经发现可以使这两个工作,并将在此处发布给其他寻找相同内容的人。也许还有其他方法可以做到这一点,但这对我有用。

所以基本上我们将使用(say) 创建一个 Cordova 应用程序: 科尔多瓦创建 testapp com.test.testapp testapp 这会给我一个文件夹结构:

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

现在在我们运行的 testapp 文件夹中:create-react-app teastappReact 这会将我的反应应用程序添加到 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 等设备对象。

此外,在您的 react 应用程序 index.html 中,可以在 public 文件夹中找到 index.html 中的 html,您可以在 Codova www 文件夹中找到该 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 中添加以下行: …… “主页”:“../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 应用程序了 cordova 构建 android/ios。

【讨论】:

  • 对于 Mac 使用 cp -a ./build/. ../www/ 而不是 robocopy,-a-r 的改进版本,构建后的点确保所有隐藏文件也被复制(如果有)
  • $ cordova plugin add cordova-plugin-whitelist 。默认情况下,只允许导航到 file:// URL。要允许其他 URL,您必须将 标签添加到您的 config.xml SO
  • 如果您想拥有特定于平台的代码,您会怎么做?仅使用 Cordova,平台特定代码位于 merges/.
  • robocopy 是一个 Windows 工具。在 Linux 中使用 "build": "react-scripts build && cp -r ./build/* ../www/"。
【解决方案2】:

我解决了这个问题。以下是我为任何寻求解决方案的人分步执行的操作:

  1. Cordova 应用目录中复制/创建新的React 项目(使用create-react-app 创建)。
  2. 清除Cordova应用的www文件夹的所有内容。
  3. cd 到 React 项目文件夹(您刚刚复制/创建)并打开 package.json
  4. dependencies 之前添加"homepage": "./", & 内部脚本将build 更改为"build": "react-scripts build &amp;&amp; robocopy .\\build ..\\www /MIR",
  5. 在同一个 (React's) 目录中执行 npm run build 并返回父 (Cordova) 文件夹,然后在所需平台中 buildemulate 您的项目。
  6. 额外提示:如果您在项目中使用 &lt;Router&gt;,请将其更改为 &lt;HashRouter&gt;,否则您将看到空白显示,因为屏幕上不会呈现任何内容。

【讨论】:

  • 谢谢你的小费,救了我!
  • 为什么不使用cp -rf ./build/ ../www/
  • @Halt 没试过。请让我们知道它是否有效。虽然以上只是 Windows 的命令。
  • 奖金小费拯救了我的一天!
  • 我尝试了各种各样的东西,这是唯一对我有用的东西。
【解决方案3】:

我认为很难找到如何解决此问题的完整指南。我从头到尾解决了这个问题,以便能够在 Windows 上的模拟 Android 设备上运行 Create React App:

首先创建一个 React 应用或使用您现有的应用。

npx create-react-app my-app

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

然后安装 Cordova:

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 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” 英特尔® 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 安装程序日志内容: === 开始记录:2020-07-10 16:39:27 === 此计算机不支持英特尔虚拟化技术 (VT-x) 或正在 Hyper-V 专用。无法安装 HAXM。请确保 Hyper-V 在 Windows 功能中被禁用,或参考 Intel HAXM 文档以获取更多信息。

不过,无论如何我都可以启动应用程序并添加一个在配置下找到的 Android 虚拟设备 (AVD)。

我选择添加Pixel XLR 系统映像。

但是再次运行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.

如果您在项目中使用&lt;Router&gt;,请将其更改为&lt;HashRouter&gt;,否则您将看到空白显示,因为屏幕上不会呈现任何内容。适用于 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 并在&lt;platform name="android"&gt; 下添加以下内容也可以解决此问题:

<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');
}

【讨论】:

    【解决方案4】:

    npm i -g react.cordova

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

    它是 cli 为您完成所有工作。 它已被修复,现在效果惊人。

    *这是我写的

    【讨论】:

    • 在推荐您自己编写的工具时,请添加免责声明(“我写了这个”)
    • 哇....谢谢你写的。我被困在让 livereload 工作在我添加 Cordova 的 create-react-app 上。这太棒了!
    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 2017-04-23
    相关资源
    最近更新 更多