Home > other >  How do i set "type:module" in nodeJs WS Library?
How do i set "type:module" in nodeJs WS Library?

Time:12-22

This has been asked a million times and answered a million times. But i still can't find a solution. The code im using is exactly the one in the Library docs usage examples:

 import WebSocket from 'ws';

const ws = new WebSocket('ws://www.host.com/path');

ws.on('open', function open() {
  ws.send('something');
});

ws.on('message', function message(data) {
  console.log('received: %s', data);
});

I haven't changed one single line of code and this is the only code i have in Node Js. But my result is the error : "Warning: to load an es module set type module in the package.json or use the .mjs extension" no matter what.

I know the answer is simply to change the "type" to "module" in "package.json" file, i have read this a thousand times. The only problems is: I have like a million package.json files in my NodeJS folder and i have no idea which one i should update. Can someone please help? I have no experience in NodeJS or WS Library,so any hint or any other solution to my problem is welcome.

CodePudding user response:

As the error message suggested, if you want to use ECMAScript modules in a Node.js application you can either:

  • Change the file extension to .mjs
  • Add "type": "module" entry at the top level to the nearest package.json

At this time Node.js will treat all other forms of input as CommonJS modules (where you use require to import).

Note

This may change in the future, and ECMAScript modules might become the default, so it is recommended to be always explicit, and if you want to use CommonJS, use .cjs extension or add "type": "commonjs" to the (nearest) package.json file.

  • Related