Seems that socket.io is AMD compatible. AMD is asynchronous module definition - the standard used by RequireJS: https://requirejs.org/docs/whyamd.html
Now, you need to use the socket.io library via RequireJS. There are two possible ways to do it:
- you just want to use socket.io in inline script
- you define your AMD file and you need socket.io in it
Let's cover case 1.
// you want to use socket.io module, so you need to call require() function to... require it
require(
/*
* in the line above you you declare an array of modules which you want to use
* in this case you need one module, socket.io
* bear in mind that there is no .js at the end!
* RequireJS assumes that the extension is .js
*/
['https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io'],
/*
* second argument of require function is a callback
* here RequireJS will inject the modules you want to use
* in this case will inject one module, socket.to
*/
(io) => {
// socket.io has been loaded and injected, now you can use it :)
var socket = io();
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});
}
);
I explained the code with the comments.
Now let's look at case 2, in this example I will define a module which will create a socket via socket.io:
// you want to define a module which uses socket.io module, so you need to call define() function to define your module
define(
/*
* in the line above you you declare an array of modules which you want to use
* in this case you need one module, socket.io
* bear in mind that there is no .js at the end!
* RequireJS assumes that the extension is .js
*/
['https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io'],
/*
* second argument of define function is a callback
* here RequireJS will inject the modules you want to use
* in this case will inject one module, socket.to
*/
(io) => {
// socket.io has been loaded and injected, now you can use it :)
var socket = io();
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});
return socket;
}
);
Now, if you want to use this socket you can use the method from case 1:
require(['path/to/your/socket/module'], (socket) => {
console.log(socket);
});
These are two most common ways to use RequireJS, hope this will help you. Any questions, just add comment and will answer them :)