Home > Enterprise >  How to import modules in a way that will not cause any errors
How to import modules in a way that will not cause any errors

Time:11-04

Currently trying to build a small website using socket.io and express. Writing in Typescript, because I like actually getting proper type errors, and transpiling the frontend code to Javascript so it actually runs in the browser.

Frontend code:

import { io, Socket } from 'socket.io-client';
// plus some relative module imports; these work just fine

// and later...
const socket = io();

// even later...
socket.emit("a message", /*some message content*/);

This script is included in index.html with <script type="module" src="${the file}"></script>. (with the actual file, of course, not a placeholder)

As far as I'm aware, this should just import the module and then do things with it.

However, when I try to view the webpage, I get an error:

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

Fair enough, imports work differently in the browser.

So I try using a bundler (webpack) to avoid anything getting imported at all, but get a different error:

main.js:1 Uncaught TypeError: Cannot read properties of undefined (reading 'emit')
// plus a bunch of traceback)

(main.js is the bundled code produced by webpack)

How am I supposed to import socket.io-client?

socket.io's official docs say to put <script src="/socket.io/socket.io.js"></script> in the html, but that just doesn't work for me, possibly because I'm using ES6 and the example in the docs uses CommonJS and puts all the frontend code in the HTML (which I don't want to have to do).

When I try the method from the docs, I just don't have access to io().

CodePudding user response:

To load the client library, use this code:

<script  src="the file"></script>

… which you already have.

Don't import it: You already have it.

CodePudding user response:

As import ... from 'socket.io-client' will try to resolve socket.io-client from the JS module system, it will fail as you didn't registered that lib yet.

Few options that should work

  1. Webpack - refer to this Socket.io with bundlers documentation
  2. For loading Socket.io as a <script> you can see live demo here. Also you can put all your JS code into app.js and load it with <script> right after the Socket.io script tag, so things stay nice and clean.
  3. Last option is to use importMap, but IMHO it more advanced and not yet supported by all browsers](https://caniuse.com/import-maps). So I would advise against it in that simple case.
  • Related