Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including additional jQuery plugins globally with Webpack 4

I am trying to make a jQuery plugin accessible to inline JavaScript using Webpack 4.

I am using the PluginProvider to make jQuery available to my website:

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

This is working fine and I can access jQuery from any page that includes my bundle.

I tried to add bootstrap-datepicker by creating a bundle called vendor.js with the following contents:

import 'bootstrap-datepicker';

I can call $('input').datepicker() from within the vendor.js bundle, however if I try and call it using an inline <script> I get:

Uncaught TypeError: $(...).datepicker is not a function

How can I configure Webpack 4 to make bootstrap-datepicker available to the global scope?


UPDATE

I've uploaded the sourcecode demonstrating this issue here: https://github.com/LondonAppDev/webpack-global-jquery-issue

It appears the issue is that the second bundle import is re-adding jQuery without the datpicker add-on. Is there a way around this?

like image 353
LondonAppDev Avatar asked Apr 12 '18 11:04

LondonAppDev


People also ask

What is provideplugin in Webpack?

Automatically load modules instead of having to import or require them everywhere.


1 Answers

I've gone a few rounds with this type of issue and had the most success with the expose-loader. In your webpack config you should set up a section for jQuery using the following expose loader configuration:

{
    test: require.resolve('jquery'),
    use: [{
        loader: 'expose-loader',
        options: 'jQuery'
    }, {
        loader: 'expose-loader',
        options: '$'
    }]
},

There is a similar SO posts here:

How to import jquery in webpack (their regex pattern did not work for me)

Expose jQuery to real Window object with Webpack

Webpack 2 loading, exposing, and bundling jquery and bootstrap

You should be able to find several other articles/posts using this configuration, it is the only one that I have successfully been able to get to work to date.

Also of note, bootstrap 4 seems to also load or do a require on jQuery internally, so if you include an import or require after your jQuery import/require and plugins, it will reinit jQuery and cause your plugins to lose scope.

like image 177
Russell Shingleton Avatar answered Oct 24 '22 01:10

Russell Shingleton