Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing jquery plugin with Webpack

Tags:

webpack

I'm trying to use bootstrap-daterangepicker with Webpack. In my view file I have the following:

define(function (require) {
    require('bootstrap-daterangepicker');

    $('#daterangepicker').daterangepicker({ ... });
});

And in webpack.config.js:

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

This results in daterangepicker is not a function. I've taken a look at daterangepicker.js, and it seems that $.fn.daterangepicker is not exported correctly. How would I do this? I've tried using imports-loader to force import jQuery, but that didn't help.

like image 636
spacek33z Avatar asked Apr 26 '15 14:04

spacek33z


People also ask

What does Webpack Provideplugin do?

Packs CommonJs/AMD modules for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand. Support loaders to preprocess files, i.e. json, jsx, es7, css, less, ... and your custom stuff.

What does expose loader do?

The expose-loader loader allows to expose a module (in whole or in part) to global object ( self , window and global ).


2 Answers

Apparently bootstrap-daterangepicker tries to load his own jQuery. Therefore $.fn.daterangepicker is not available in 'my' jQuery. I've forced bootstrap-daterangepicker to include my jQuery with this line in webpack.config.js:

resolve: {
    alias: {
        'jquery': require.resolve('jquery'),
    }
}
like image 140
spacek33z Avatar answered Sep 18 '22 23:09

spacek33z


The webpack 'resolve' option didn't help me but @spacek33z comments lead me to realize that my Angular component's linked element wasn't a jQuery element but an ordinary DOM element. The reason why was that Angular was using its own jqLite vs. the real jQuery.

Searching for why Angular wasn't finding the real jQuery I found the question 'Webpack: how to make angular auto-detect jQuery and use it as angular.element instead of jqLite?' that helped me realize Angular needs window.jQuery.

So this seems to be the proper webpack.conf.js incantation for me:

new webpack.ProvidePlugin({
         'jQuery': 'jquery',
  'window.jQuery': 'jquery',
         'jquery': 'jquery',
  'window.jquery': 'jquery',
         '$'     : 'jquery',
  'window.$'     : 'jquery'
}),
like image 25
Rob Light Avatar answered Sep 20 '22 23:09

Rob Light