socket.io server node.js and esbuild

Viewed 154

I'm trying to setup a server (API) with socket.io and a client connected between them, this is my esbuild config using hot-reload with esbuild-serve (client it's running on port 7000 and BE on 8000)

import esbuildServe from 'esbuild-serve'

esbuildServe(
  {
    logLevel: 'info',
    entryPoints: ['src/index.js'],
    // platform: 'node',
    // target: ['node16.13'],
    // format: 'cjs',
    bundle: true,
    outfile: 'dist/main.js',
    external: ['socket.io'],
    sourcemap: true,
    minify: true
  },
  {
    port: 8000,
    root: 'dist'
  }
)

and this is my project tree, Docker simply use a node 16 base image and run the command node esbuild.config.js to start dev hot-reload server and instantiate the 2 node.js images exposing 7000(client), 8000(BE), 8001(websocket port)

enter image description here

Client code seems to work OK:

import { io } from 'socket.io-client'

const socket = io('localhost:8001')

socket.on('connect', (socket) => {
  console.log(socket)
})

socket.on('message', function (data) {
  console.log('message', data.message)
})

and this is the BE code that doesn't seem to be bundled correctly

// import { createServer } from 'http'
import { Server } from 'socket.io'

// const httpServer = createServer()

// const io = new Server(httpServer, {
const io = new Server({
  port: 8001,
  cors: {
    origin: '*'
  }
})


io.on('connection', function (socket) {
  socket.emit('message', { message: 'A new user has joined!' })
})

// httpServer.listen(8001)

// io.emit('connection', (socket) => {
//   return socket
// })

By removing the external: ['socket.io'], it start complaining about missing dependencies from the node_module so I enable these settings as it suggest:

platform: 'node',
target: ['node16.13'],
format: 'cjs',

But then the compiled version once I load localhost:8000 I have this error Uncaught ReferenceError: require is not defined

UPDATE:

I've changed the format cjs to esm and now seems to compile but not it's throwing this new error:

Uncaught TypeError: Failed to resolve module specifier "socket.io". Relative references must start with either "/", "./", or "../"

0 Answers
Related