Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import socket.io npm packege - Nodejs

const socketio = new Server();

import Server from 'socket.io';
SyntaxError: The requested module 'socket.io' does not provide an export named 'default'

like image 839
John John Avatar asked Dec 23 '22 16:12

John John


2 Answers

There are two kinds of exports: named exports (several per module) and default exports (one per module). It is possible to use both at the same time, but usually it is best to keep them separate.

Why are you receiving this error: The import statement you wrote, provides the Server which is not a default export. If socket.io had actually exported Server as below, then you would not get an error.

module.exports = {
  //Other exports
  Server as default
}

You could have done this:

import * as io from "socket.io"
import express from 'express';
import { createServer } from 'http';

const app = express(); 
const server = createServer(app); 
const socketio = new io.Server(server);

Edit:

You can import socket.io like this:

import { Server } from 'socket.io';
import express from 'express';
import { createServer } from 'http';

const app = express(); 
const server = createServer(app); 
const socketio = new Server(server);
like image 57
Megh Agarwal Avatar answered Jan 02 '23 15:01

Megh Agarwal


I can not beleive Socket.io is making it so difficult to import their npm package.

Here is the answer. Thank you @MeghAgarwal

import { Server } from 'socket.io';
import express from 'express';
import { createServer } from 'http';

const app = express(); 
const server = createServer(app); 
const socketio = new Server(server);
like image 33
John John Avatar answered Jan 02 '23 14:01

John John