【问题标题】:Requiring unknown module "crypto" in react-native environment在本机环境中需要未知模块“加密”
【发布时间】:2015-07-02 09:43:41
【问题描述】:

我正在使用 react-native 编写一个简单的 Twitter 应用程序。使用 twit 模块获取 Twitter 提要和流。下面是代码,它工作正常节点。但是,当包含在我的 react-native 应用程序中时,看到错误“需要未知模块“加密””。依赖似乎是 myapp->twit->oauth->crypto (这是节点 v0.12.2 的一部分)。有什么建议可以在 react-native 环境中工作吗?

var Twit = require('twit')
var T = new Twit({
    consumer_key:''
  , consumer_secret:''
  , access_token:''
  , access_token_secret:''
})
var filtered_tweets=[];
var error;
var isSuccess=false;

function getTweets(searchString){
    T.get('search/tweets',{q:searchString, count:100}, getResponse);
    }

function getResponse(err,data,response){
        if(err) { 
            handleGetErr(err); 
        }
        handleGetData(data.statuses);
    }

function handleGetErr(err){

    enter code here

    error = err;
    }

function handleGetData(data){
    data.map(function(tweet){
      var twit={
        twit:tweet.id,
        created_at:tweet.created_at,
        text:tweet.text,
        retweet_count:tweet.retweet_count,
        favorite_count:tweet.favorite_count
      };
      filtered_tweets.push(twit);
    });
    console.log(filtered_tweets);
    isSuccess=true;
}
getTweets("@sahaswaranamam");
module.exports = getTweets;

![附][2]

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    crypto 模块是一个内置的 Node 模块; React Native 在 JavaScriptCore(在设备或模拟器上)和 Chrome 本身(在使用 Chrome 调试时)上运行 JS,因此依赖于内置 Node.js 模块的模块将无法工作。有关更多信息,请参阅 React Native 文档的 the JavaScript Runtime section

    我不确定集成到 React Native 应用程序中会有多难,但是像 Browserify 这样的浏览器模块捆绑器通常具有核心 Node.js 模块的浏览器版本,例如 this one for crypto

    【讨论】:

    • 谢谢。 JavaScriptCore 中是否还有其他类似的 oauth 实现作为示例..
    【解决方案2】:

    如果您按照@emmby 的建议使用rn-nodeify,那么您可以使用react-native-crypto。自述文件中的说明:

    1. 安装

      npm i --save react-native-crypto
      # install peer deps
      npm i --save react-native-randombytes
      react-native link react-native-randombytes
      # install latest rn-nodeify
      npm i --save-dev mvayngrib/rn-nodeify
      # install node core shims and recursively hack package.json files
      # in ./node_modules to add/update the "browser"/"react-native"
      # field with relevant mappings
      ./node_modules/.bin/rn-nodeify --hack --install
      
    2. rn-nodeify会在项目根目录下创建shim.js

      // index.ios.js or index.android.js
      // make sure you use `import` and not require!  
      import './shim.js'
      // ...the rest of your code
      

    rn-nodeify 也声明:

    如果您正在寻找更明智的方法,请查看ReactNativify。我自己没有测试过,但我认为philikon 会很乐意提供帮助


    使用 ReactNativify,您可以创建一个 rn-cli.config.js,然后在 transformer.js 中让 Babel 使用 babel-plugin-rewrite-require 转换捆绑包依赖项:

    // The following plugin will rewrite imports. Reimplementations of node
    // libraries such as `assert`, `buffer`, etc. will be picked up
    // automatically by the React Native packager.  All other built-in node
    // libraries get rewritten to their browserify counterpart.
    
    [require('babel-plugin-rewrite-require'), {
      aliases: {
        crypto: 'crypto-browserify',
        // ...
      },
      throwForNonStringLiteral: true,
    }]
    

    注意:你也可以在没有这两个js文件的情况下直接在.babelrc中这样做)

    注意 2:虽然 ReactNativify 是更清洁的方式,但它仍然给我在连接 crypto.getRandomValues 以在 RN 中用于生产使用的问题。请参阅 this question

    【讨论】:

    • 您可以在rn-cli.config.js 中导出extraNodeModules 并覆盖节点模块,而不是在transformer.js 中创建自己的babel 转换。有关更多信息,请查看 ReactNativify 的 repo github.com/philikon/ReactNativify/issues/4 上的此问题
    • @Arnold 成功完成所有过程后,我收到此错误 Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)
    • 对不起@Chandni,但这对我来说太久远了,我无法提供帮助,同时事情可能已经发生了变化。如果您在解决与答案相关的问题方面获得了新的见解,我很乐意更新文本(或者您可以自己进行更新)。
    【解决方案3】:

    您可以使用 rn-nodeify 模块在 react-native 上获取 crypto

    package.json 中将rn-nodeify 添加到您的devDependencies

    "devDependencies": {
      "rn-nodeify": "^6.0.1"
    }
    

    将以下内容添加到同一文件的scripts 部分:

    "scripts": {
      …
      "postinstall": "node_modules/.bin/rn-nodeify --install crypto --hack"
    }
    

    注意 rn-nodeify 会修改你的 package.json。

    更多信息在这里:https://www.npmjs.com/package/rn-nodeify

    【讨论】:

    • 如果我的 react-native 依赖项之一使用“加密”,这会有所帮助吗?我尝试按照您编写的说明进行操作,但似乎不起作用。
    • @emmby 成功完成所有过程后,我收到此错误 Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)
    【解决方案4】:

    React Native 打包器在底层使用 Babel。这意味着您可以使用babel-plugin-rewrite-require Babel plugin 将所有require('crypto') 调用重写为require('crypto-browserify'),假设后者安装在您的node_modules 中。

    截至 2016 年 1 月,您可以使用 .babelrc 文件来定义可选配置,因此这变得非常容易。首先,安装依赖:

    npm install --save crypto-browserify
    npm install --save-dev babel-plugin-rewrite-require
    

    然后将插件配置添加到您的.babelrc 文件中:

    {
      "presets": ["react-native"],
      "plugins": [
        ["babel-plugin-rewrite-require", {
          "aliases": {
            "crypto": "crypto-browserify"
          }
        }]
      ]
    }
    

    重启打包器,应该就是这样了。

    这与ReactNativify 使用的方法相同,只是这里我们使用.babelrc 而不是定义自定义转换器。 ReactNativify 写的时候不支持,所以他们不得不采用更复杂的解决方案。请参阅 this file from ReactNativify 了解几乎完整的节点 polyfill 列表。

    【讨论】:

    • 我理解您的回答,但由于某种原因它无法正常工作。 “UnableToResolveError:无法从 /Users/myproject/node_modules/browserify-sign/browser/index.js 解析模块流:”
    • 你试图重写什么模块?你的node_modules 目录中有stream 包吗?
    • @skozin 感谢您的回复!我仍然无法使其适用于依赖加密的库。该库被称为:otplib。您找到处理这些案件的方法了吗?我设法用 rn-nodeify 破解了它,但它超级敏捷
    • @skozin 成功完成所有过程后,我收到此错误 Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)
    【解决方案5】:

    在我的 React Native 应用程序中实现 Twilio 包时,我遇到了同样的问题,并且 React Native 打破了加密依赖关系。

    作为一种解决方法,我最终创建了一个单独的、独立的 Node/Express 应用程序来充当我的服务器并处理我拥有的 Twilio 逻辑。这样,我从我的 React Native 应用程序中删除了所有 Twilio 逻辑并将其移至 Node.js。然后,我使用 fetch 在 React Native 中调用了我的 Express 路由,这触发了我希望在 Twilio 中实现的功能。如果您不熟悉 fetch 这是一个很好的起点 - Making AJAX calls with Fetch in React Native

    此外,这是我关于破坏我的应用程序的加密依赖项的问题:

    twilio-react-native-unable-to-resolve-module-crypto

    【讨论】:

      【解决方案6】:

      据我所知,amazon-cognito-identity-js 使用 crypto-js 3.3.0 没有任何额外的魔法......如果该版本的软件包有效,那么也许可以尝试一下。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-14
        • 1970-01-01
        相关资源
        最近更新 更多