1

I am trying to use socket.io-client in my React app and am running into an odd problem. Deep inside engine.io (required by socket.io-client) there is a file called websocket.js with the following bit of code:

if (typeof window === 'undefined') {
  try {
    NodeWebSocket = require('ws');
  } catch (e) { }
}

Since window is not undefined, you might think that this code does nothing, but you’d be wrong.

My packager (the standard React Native packager, so far as I know) goes through all the Javascript files and looks for all the import and require commands, and packages up the files they refer to.

The ws module contains a file called WebSocket.js, which intended for Node.js and makes use of Node.js modules like url.js and http.js, which of course do not exist in React, so the attempt at packaging fails.

Deleting those five lines fixed the problem and everything worked, but there must be a better way. Can I tell the packager to exclude certain modules?

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
  • FYI there is an open issue at React Native Product Pains on this: https://productpains.com/post/react-native/packager-support-resolvealias-ala-webpack/ - and there doesn't seem to be a great workaround. – jevakallio Jan 28 '17 at 21:20

3 Answers3

0

I wasn't able to reproduce your problem, but you can try to blacklist the ws package.

How to blacklist specific node_modules of my package's dependencies in react-native's packager?

Community
  • 1
  • 1
henkimon
  • 1,433
  • 2
  • 15
  • 27
  • I found out the reason you couldn't repro. I was using a slightly older version of the React packager, which did not understand `false` as a value in the `browser` object of package.json. – Michael Lorton Feb 08 '17 at 23:04
0

You can try the below code :

  if (typeof window === 'undefined') {
      try {
        var wsNode = 'ws' // store node module name in a string
        NodeWebSocket = require(wsNode); // dynamic require will exclude the node module to get bundled in react-native
      } catch (e) { }
    }
Ayush Nawani
  • 654
  • 6
  • 16
  • That's exactly what I did do, but going into production would require forking the engine-io package and the socket-io package. I was looking for another solution. – Michael Lorton Feb 07 '17 at 19:32
0

I haven't solve my problem as posed, but I figured out what was going on, why I was having difficulties other users were not.

In the file node_modules/engine.io-client/package.json was the following entry:

  "browser": {
    "ws": false,
    "xmlhttprequest-ssl": "./lib/xmlhttprequest.js"
  },

My venerable version of the React packager did not understand the "false" to mean "skip including ws [WebSockets] when you are building for the client side". Upgrading the packager made the problem go away.

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144