How to load signalr.js in webpack inside Angular 2

2019-02-17 00:15发布

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?

2条回答
混吃等死
2楼-- · 2019-02-17 00:57

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 = (summary) => {
                // 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.

查看更多
The star\"
3楼-- · 2019-02-17 01:04

Clean solution: use expose-loader !!

npm install expose-loader --save-dev

inside your vendor.ts

import 'expose-loader?jQuery!jquery';
import '../node_modules/signalr/jquery.signalR.js';

inside your webpack.config.ts

new ProvidePlugin({ jQuery: 'jquery', $: 'jquery', jquery: 'jquery' })

Explanation: The jquery.signalR.js script is indeed not written as a umd module. Which makes it by default, not to be loadable by webpack. It doesn't require jquery, but assumes that Jquery lives on the global variable window.jQuery. We can make this work in webpack by importing the jquery module with the expose-loader. This loader will make sure that the exported value of jquery, is exposed to the jQuery global var. Thus allowing to load the signalr.js script as the next module.

Also if you want to later use signalr by using $, you also will have to use the provideplugin for the jquery module. inside webpack.config.js

查看更多
登录 后发表回答