Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include jQuery in Angular2 with webpack and access it from component

I want to include jQuery and SignalR in my Angular2-Application and wire everything up with webpack.

I therefore installed jQuery via npm.

package.json

"dependencies": {
    // ...
    "jquery": "2.1.4",
    // ...
  },

Files and folders are installed correctly.

I now target these files in my vendor.ts to get webpack to find and include them:

import 'jquery';
import 'bootstrap/dist/js/bootstrap.js';
import '../../bower_components/signalr/jquery.signalR';

And webpack gets these files and wires them up. I can see this in my vendor.js. jQuery is present there. Also the jquery signalR-File.

My webpack.config:

var webpack = require("webpack");
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        "vendor": "./wwwroot/app/vendor",
        "polyfills": "./wwwroot/app/polyfills",
        "app": "./wwwroot/app/boot"
    },
    output: {
        path: __dirname,
        filename: "[name]-[hash:8].bundle.js"
    },
    resolve: {
        extensions: ['', '.ts', '.js', '.html']
    },
    devtool: 'source-map',
    module: {
        loaders: [
            {
                test: /\.ts/,
                loaders: ['ts-loader'],
                exclude: /node_modules/
            },
            {
                test: /\.html$/,
                loader: 'html'
            },
            {
                test: /\.css$/,
                loader: 'raw'
            }
        ]
    },
    plugins: [
         new webpack.ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery',
            jquery: 'jquery'
        }),
        //new webpack.optimize.DedupePlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: ["app", "vendor", "polyfills"]
        })
    ]
}

Loaded in my index like:

<script src="js/polyfills-2eba52f6.bundle.js"></script>
<script src="js/vendor-2eba52f6.bundle.js"></script>
<script src="js/app-2eba52f6.bundle.js"></script>

But when I try to use it in my angular2 component like:

// ...

declare var jQuery:any;
declare var $:any;

@Injectable()
export class MySignalRService {

    private connection;

    constructor() {

        this.connection = $.hubConnection(CONFIGURATION.baseUrls.server + 'signalr/');
        jQuery.hubConnection(CONFIGURATION.baseUrls.server + 'signalr/');

        // ...
    }

    //...

I alway get the message that

$.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 can I do to access the singalr-Function in webpack?

BR Tenoda

like image 941
Tenoda Avatar asked Sep 10 '16 08:09

Tenoda


2 Answers

Clean solution: use expose-loader !!

npm install expose-loader --save-dev

inside your vendor.ts

> import 'expose?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. The jquery.signalR.js script 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

like image 145
hannes neukermans Avatar answered Oct 21 '22 21:10

hannes neukermans


I investigated your problem and found the following solutions:

1) Use

window.jQuery = require("jquery");

to import jQuery in your entry file

2) Change your webpack.config.js

 new webpack.ProvidePlugin({
   jQuery: 'jquery',
   $: 'jquery',
   jquery: 'jquery',
   'window.jQuery': 'jquery' <== add this line
 }),

And then in your entry file:

import 'jquery';
like image 28
yurzui Avatar answered Oct 21 '22 22:10

yurzui