Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load signalr.js in webpack inside Angular 2

I always get a message saying:

$.hubConnection is not a function

Error: jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file. consoling out "$" and "jquery" is undefined.

What do I need to do, to get signalr working using webpack?

like image 687
hannes neukermans Avatar asked Oct 13 '16 20:10

hannes neukermans


1 Answers

Thanks to hannes and this guide from Microsoft I managed to get SignalR working with Webpack and TypeScript using the ES6 syntax.

Before:

///<reference path="./vendor/typings/signalr/signalr.d.ts"/>

interface SignalR {
    myHub: Some.Stuff.IMyHubProxy;
}

namespace MyWebsite.Stuff {
    export class SignalRConnectionService {
        ...
        public start() {
            var myHubProxy = $.connection.myHub;

            myHubProxy.client.onSomethingChanged = (eventArgs) => {
                // do stuff
            };

            $.connection.hub.start();
        }
    }
}

After:

import "signalR";

export class SignalRConnectionService {
    public start() {
        ...
        const hubConnection = $.hubConnection();
        const myHubProxy = hubConnection.createHubProxy('myHub');

        myHubProxy.on('onSomethingChanged', (summary) => {
            // do stuff
        });

        hubConnection.start();
    }
}

webpack.config.js:

plugins: [
    new webpack.ProvidePlugin({
        $: "jquery",
        'window.jQuery': 'jquery',
        jQuery: "jquery"
    })
]

packages.json:

"dependencies": {
  "jquery": "~2.1.4",
  "signalr": "~2.2.3"
}

NB: You will also need to remove loading of <script src="/signalR/hubs"/> as it's no longer needed.

like image 98
Vedran Avatar answered Sep 23 '22 10:09

Vedran