【问题标题】:How to conditionally import dependencies in a module shared between React (Next.js) and React Native?如何有条件地导入 React (Next.js) 和 React Native 之间共享的模块中的依赖项?
【发布时间】:2020-12-09 20:00:49
【问题描述】:

我想为 React (Next.js) Web 应用和 React Native 移动应用构建一个共享的 Typescript 模块。

此模块将处理对后端 (Firebase) 的所有调用以及使用上下文 API 进行状态管理。

问题在于 React 和 React Native 不会为相同的任务使用相同的包。

基本上我需要做的:

import react from 'react',
if (platform == 'mobile') {
  import app from '@react-native-firebase/app'
  import firestore from '@react-native-firebase/firestore'
  import auth from '@react-native-firebase/auth'
  import storage from '@react-native-firebase/storage'
} else if (platform == 'web') {
  import app from 'firebase/app'
  import firestore from 'firebase/firestore'
  import auth from 'firebase/auth'
  import storage from 'firebase/storage'  
} else // throw some error

当然,这段代码是行不通的。有解决办法吗?

谢谢

【问题讨论】:

  • 您可以在构建中包含一个步骤,该步骤采用环境变量并在实际构建之前使用正确的导入解析和编辑文件

标签: javascript reactjs firebase react-native next.js


【解决方案1】:

要区分 Web 应用程序/ react-native 移动应用程序的请求,您可以查看移动应用程序不支持的选项。例如,localStorage 是浏览器上的一个窗口方法,它不适用于移动设备。要决定您可以检查的平台,

            if(typeof(localStorage)) {
               //Browser module initialization
              }
            else {
              //Mobile module initialization like AsyncStorage
              }

【讨论】:

    【解决方案2】:

    您可以检查平台上是否存在窗口

    if(windows ==underfined ) {
    // mobile plateforme
    }else{
    // web plateforme
    }
    

    【讨论】:

      【解决方案3】:

      https://webpack.js.org/configuration/resolve/#resolvealias

      执行两个单独的构建以为每个平台生成 2 个工件 1 并使用 webpack 解析别名来更改默认导入的来源。

      导入不能在 ESM 中有条件地解决,因为它们总是被提升;您可以使用动态导入,但是这些返回的 Promise 会使它们更难使用。

      【讨论】:

        【解决方案4】:

        我目前使用 2 个文件:

        directory
        | - imports.ts
        | - imports.native.ts
        

        例如当我写的时候:

        import { package1, package2 } from '../directory/imports.ts'
        

        React Native 知道它需要从 imports.native.ts 导入,而不是从 imports.ts 导入。这是一个内置功能。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-04-06
          • 2015-10-28
          • 2021-08-26
          • 2016-03-22
          • 2021-07-16
          • 1970-01-01
          • 2016-03-17
          • 2019-02-15
          相关资源
          最近更新 更多