0

I have added a require statement to require the ws library inside an if statement so that it will be imported only if its not the browser. For example, require ws only for the tests.

if (!process.browser) {
  webSocketLinkConfig.webSocketImpl = require('ws');
}

But the problem is, even though the rest of the assignment webSocketLinkConfig.webSocketImpl doesn't happen, the require gets executed and I get a warning in the browser saying Module not found: Can't resolve 'bufferutil' in '/Users/pubudu/Projects/FleetManager/fm-dash-front/node_modules/ws/lib'

Any idea what's happening and how to fix it?

This is a react app built with create-react-app.

THpubs
  • 7,804
  • 16
  • 68
  • 143
  • Hi maybe this thread can help you https://stackoverflow.com/questions/20315434/node-js-asynchronous-module-loading – t3__rry Jul 16 '18 at 13:25
  • Are there chances you don't have process.browser set? It is specific to your build, which wasn't shown in the question. – Estus Flask Jul 16 '18 at 13:31
  • @estus It has been set correctly but still gets the issue. If I add some code inside that if block it won't get executed. But this require does. – THpubs Jul 16 '18 at 16:03
  • Again, this is specific to how you build client side app, nothing else. The question doesn't contain necessary information. – Estus Flask Jul 16 '18 at 16:43
  • @estus Ah sorry. It's a `react` app built with `create-react-app`. – THpubs Jul 16 '18 at 17:58

1 Answers1

0

I have not used process.broswer before, so it may be possible you do not have it set. I made a sandbox for getting whether or not you are running in a browser by using navigator.

The navigator object contains information about the browser. - w3schools

if (!navigator) {
  webSocketLinkConfig.webSocketImpl = require('ws');
}

Here is a CodeSandbox example which (using console) shows how you can use navigator to tell if you're running your code in a browser. Hope this helps.

Sophia Price
  • 848
  • 11
  • 17
  • `navigator` is not defined in Node, that will throw if run in node. you should check it navigator is present first, also, you can use `window` that isn't defined in node too. – Marcos Casagrande Jul 16 '18 at 13:43
  • Used navigator and window but both have the issue. Both return undefined in node and works on the browser. I don't think the problem is there. – THpubs Jul 16 '18 at 15:52
  • Does checking for undefined instead work? i.e. if (navigator === undefined) { // do something } else { // do something else } – Sophia Price Jul 17 '18 at 11:00