Is there a feasible way to import socket.io client to a script file separate from the html?

Viewed 13

I'm making a multiplayer word game with Node, Express, Vanilla JS and socket.io. Currently everything is working as it should on the client side, with the very big but that all code has to be in the ejs/html file in order to run.

I've tried:

  • Changing to type=module to use the ES6 dynamic import to

import io from '../node_modules/socket.io/client-dist/socket.io.js'

this doesn't work, I guess because the local host pathway isn't public

require(...

Doesn't work, since it's on the client side

const socket = io('http//local_ip:3000')

This was the most promising option but returns a recurring GET http://http/socket.io/?EIO=4&transport=polling&t=OCFbpzZ net::ERR_NAME_NOT_RESOLVED error

And thus I'm rewriting most of the client js into a script tag, which feels straight up sacriligious. I feel like there just has to be a better way

So basically:

THIS works:

...
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
</script>
</body>

Is there any way to define this in an external js file instead?

A fun quirk is that I can still use socket methods in the linked js file, but only in functions, which I guess has to do with the var scope?

0 Answers
Related