5
const socketio = new Server();

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

Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
John John
  • 1,305
  • 2
  • 16
  • 37

4 Answers4

10

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);
Megh Agarwal
  • 216
  • 1
  • 7
2

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);
John John
  • 1,305
  • 2
  • 16
  • 37
1

As of v3, the correct way to do it is:


const httpServer = require('http').createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('Content-Length', Buffer.byteLength(content));
  res.end(content);
});
// Or const httpServer = require('http').createServer(app) if you use express

const io = require('socket.io')(httpServer);

And if you import * as io from 'socket.io', you got to call io.io(httpServer). I ran into the same error

0

I got the same error. This works for me

const express = require('express');
const app = express();

const io = require("socket.io")(80);
const http = require("http");
const server = http.createServer(app);
Azad Kumar
  • 13
  • 2