How to import socket.io-client in a angular 2 application?
In order to register the module so you can import it, you need to include it in you SystemJS configuration.
System.config({ packages: { ... "socket.io-client": {"defaultExtension": "js"} }, map: { "socket.io-client": "node_modules/socket.io-client/socket.io.js" }});
And change your import to:
import io from 'socket.io-client';
import * as io from "socket.io-client
Also, you don't need the import in the script tag anymore, so remove:
<script src="node_modules/socket.io-client/socket.io.js"></script>
Finally, if you like to add the typings, add in your typings.json
:
{ "ambientDependencies": { ... "socket-io-client":"github:DefinitelyTyped/DefinitelyTyped/socket.io-client/socket.io-client.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd" }}
P.S. Int the future, change the hash in the typings to the latest commit hash.
This is a late answer since I just had this problem and installing correct types via npm solved it for me:
npm install @types/socket.io-client --save
This package contains type definitions for socket.io-client
, so if you are getting type errors this should fix it.
I also had problems while trying to import socket.io into my project and here is how I resolved it.
- Use Angular 2 (rc.6)
- Based on Systemjs
- From the skeleton on Angular 2samples
- Node : 5.3.0
- Mac OSX El Capitan
Here we go :
1) Edit your systemjs.config.js file as it :
/** * System configuration for Angular 2 samples * Adjust as necessary for your application needs. */(function (global) { System.config({ paths: { // paths serve as alias 'npm:': 'node_modules/' }, map: { ... here my stuff ... "socket.io-client": 'npm:socket.io-client' }, packages: { ... here my stuff ... "socket.io-client": { main: './socket.io.js' } } });})(this);
2) Open your project in a shell then exec the following line :usually we tell you to do :
npm install socket.io-client --savetypings install socket.io-client --save --ambient
But you might received a message that told you that the ambiant flag is deprecated and that you should use global instead. But you'll quickly see that it won't work either. So i propose you something else (well errors logs will give you hints, but you probably won't understand it if you didn't go there before) :
typings install dt~socket.io-client --save --global
3) Open your component that require socket.io then add at the top of your file :
import * as io from "socket.io-client";
then go down and add :
export class MessageComponent implements OnInit { socket:any = null; constructor() { this.socket = io('http://localhost:1337'); } ... here my stuff ...}
Where 1337 is the port of your node server containing socket.io that has been launched.
Now, all is ready, you can directly make your request :
this.socket.emit('sendMessage', {content:'it works !'});
Hope I help :), good luck with your project