Search code examples
jquerywebpackbootstrap-tags-input

How to import and use a jQuery library via Webpack?


I'm using VueJS with Webpack, and I'm trying to use this jQuery tags input library. Given its needs, I'm including jQuery as a global:

// in webpack.config.js
new webpack.ProvidePlugin({
  $: "jquery",
  jQuery: "jquery",
  "window.jQuery": "jquery",
  "jQuery.tagsinput": "bootstrap-tagsinput"
})

// in main JS
import jQuery from 'jquery';

That all works, but the issue is being able to get this other library in. I can require it into the main JS file (require('../node_modules/bootstrap-tagsinput/dist/bootstrap-tagsinput.js'); ) and that gets it into my vendor file, but it doesn't execute and nothing happens.

What am I doing wrong? Do I need to use import-loader somehow, or some shimming thing - something else entirely?


Solution

  • Okay, I got it working. Here's what I did:

    1. In webpack.config.js:

      plugins : [
       // ...
        new webpack.ProvidePlugin({
          $: "jquery",
          jQuery: "jquery",
          "window.jQuery": "jquery",
          "jQuery.tagsinput": "bootstrap-tagsinput"
        })
      ]
      
    2. In my main Javascript file:

      // other imports, etc.
      require('imports?$=jquery!../node_modules/bootstrap-tagsinput/dist/bootstrap-tagsinput.js');
      

    Note that this requires the use of the imports-loader.

    1. In my component:

      export default {
        // ...
        ready: function() {
      
            this.$watch('MY_MODEL', function(elt) {
                $('input[data-role=tagsinput]').tagsinput();
            });
      
        }
      }
      

    Note that you need to manually apply .tagsInput() here. The .$watch is to make sure that the element is actually rendered on the page. If you just put the .tagsinput() call straight into ready, it won't fire because the element hasn't necessarily been added to the DOM. You can also rig up a solution using window.requestAnimationFrame if you need to.