Socket.io 1.0.x not compatible with require.js?

Anytime when I try to load socket.io 1.0.x after require.js, it creates

Unprepared ReferenceError: io not defined

<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>
<script type="text/javascript">
    var socket = io('http://localhost');
</script> 

But if I put socket.io before require.js, this will not result in an error:

<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js"></script>
<script type="text/javascript">
    var socket = io('http://localhost');
</script> 

This, of course, means that socket.io cannot be loaded with require.js as follows:

requirejs.config({
    paths: { 

        'socketio' : ['https://cdn.socket.io/socket.io-1.0.6'],


    },
    shim: {

        'socketio': {
            exports: 'io'
        }
    }
});

require(['socketio'], function(io){

    console.log(window.io); //undefined


})
+4
source share
3 answers

Socket.io 0.x

with socket.io 0.x you need to export io to require.js configuration:

shim: {   
  'socket.io-client': {    
     exports: 'io'    
   } 
}

and your js file:

define(['socket.io-client'], function () {
  // io is exported here    

  var socket = io.connect ...
}

Socket.io 1.x

with socket.io 1.x, no need to export io to require.js configuration file

and your js file:

define(['socket.io-client'], function (io) {
  // io an argument of the function   

  var socket = io.connect ...
}

io , require.js, .

, socket.io-client socket.io

0

RequireJS require define... socket.io js .

socket.io AMD

0

bower (ng-socket) socket.io-client RequireJS. ng-socket , io undefined, .

, startSocketIo.js:

define([
  'socket.io-client'],function(io) {
  window.io = io;
});

deps :

deps: [
  './startSocketIo'
],

script , bower requirejs js.

0
source

Source: https://habr.com/ru/post/1546224/


All Articles