[jquery] How to use a jQuery plugin inside Vue

I'm building a web application inside VueJS but I encounter a problem. I want to use a jQuery extension (cropit to be specific) but I don't know how to instantiate/require/import it the right way without getting errors.

I'm using de official CLI tool and de webpack template for my App.

I included jQuery like this in my main.js file:

import jQuery from 'jQuery'
window.jQuery = jQuery

Now I'm building an image editor component where I want to instantiate crept like this:

export default {
  ready () {
    $(document).ready(function ($) {
      $('#image-cropper-wrapper-element').cropit({ /* options */ })
    })
  },
 }

But I keep getting errors...Now my question is how to properly instantiate jQuery and plugins via NPM/Webpack/Vue?

Thanks in advance!

This question is related to jquery jquery-plugins webpack vue.js

The answer is


Option #1: Use ProvidePlugin

Add the ProvidePlugin to the plugins array in both build/webpack.dev.conf.js and build/webpack.prod.conf.js so that jQuery becomes globally available to all your modules:

plugins: [

  // ...

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

Option #2: Use Expose Loader module for webpack

As @TremendusApps suggests in his answer, add the Expose Loader package:

npm install expose-loader --save-dev

Use in your entry point main.js like this:

import 'expose?$!expose?jQuery!jquery'

// ...

First install jquery using npm,

npm install jquery --save

I use:

global.jQuery = require('jquery');
var $ = global.jQuery;
window.$ = $;

Suppose you have Vue project created with vue-cli (e.g. vue init webpack my-project). Go to project dir and run

npm install jquery --save

Open file build/webpack.base.conf.js and add plugins:

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

Also at top of file add:

const webpack = require('webpack')

If you are using ESLint, open .eslintrc.js and add next globals: {

module.exports = {
  globals: {
    "$": true,
    "jQuery": true
  },
  ...

Now you are ready to go. Use $ anywhere in your js.

NOTE You don't need to include expose loader or any other stuff to use this.

Originally from https://maketips.net/tip/223/how-to-include-jquery-into-vuejs


You need to use either the globals loader or expose loader to ensure that webpack includes the jQuery lib in your source code output and so that it doesn't throw errors when your use $ in your components.

// example with expose loader:
npm i --save-dev expose-loader

// somewhere, import (require) this jquery, but pipe it through the expose loader
require('expose?$!expose?jQuery!jquery')

If you prefer, you can import (require) it directly within your webpack config as a point of entry, so I understand, but I don't have an example of this to hand

Alternatively, you can use the globals loader like this: https://www.npmjs.com/package/globals-loader


import jquery within <script> tag in your vue file.

I think this is the easiest way.

For example,

<script>
import $ from "jquery";

export default {
    name: 'welcome',
    mounted: function() {
        window.setTimeout(function() {
            $('.logo').css('opacity', 0);   
        }, 1000);
    } 
}
</script>

There's a much, much easier way. Do this:

MyComponent.vue

<template>
  stuff here
</template>
<script>
  import $ from 'jquery';
  import 'selectize';

  $(function() {
      // use jquery
      $('body').css('background-color', 'orange');

      // use selectize, s jquery plugin
      $('#myselect').selectize( options go here );
  });

</script>

Make sure JQuery is installed first with npm install jquery. Do the same with your plugin.


I use it like this:

import jQuery from 'jQuery'

ready: function() {
    var self = this;
    jQuery(window).resize(function () {
      self.$refs.thisherechart.drawChart();
    })
  },

Step 1 We place ourselves with the terminal in the folder of our project and install JQuery through npm or yarn.

npm install jquery --save

Step 2 Within our file where we want to use JQuery, for example app.js (resources/js/app.js), in the script section we include the following code.

// We import JQuery
const $ = require('jquery');
// We declare it globally
window.$ = $;

// You can use it now
$('body').css('background-color', 'orange');

// Here you can add the code for different plugins

run npm install jquery --save

then on your root component, place this

global.jQuery = require('../node_modules/jquery/dist/jquery.js');
var $ = global.jQuery;

Do not forget to export it to enable you to use it with other components

export default {
  name: 'App',
  components: {$}
}

Questions with jquery tag:

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.? How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) Only on Firefox "Loading failed for the <script> with source" How to prevent page from reloading after form submit - JQuery Vue component event after render How to use jQuery Plugin with Angular 4? How to disable a ts rule for a specific line? Bootstrap 4 File Input How to force reloading a page when using browser back button? Datatables Select All Checkbox Unable to preventDefault inside passive event listener Getting Error "Form submission canceled because the form is not connected" How to create multiple page app using react Set height of chart in Chart.js console.log(result) returns [object Object]. How do I get result.name? Setting and getting localStorage with jQuery JQuery: if div is visible Using OR operator in a jquery if statement Deprecation warning in Moment.js - Not in a recognized ISO format How to use aria-expanded="true" to change a css property DataTables: Cannot read property style of undefined Disable Chrome strict MIME type checking Consider marking event handler as 'passive' to make the page more responsive Cannot open local file - Chrome: Not allowed to load local resource "Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project what is right way to do API call in react js? why $(window).load() is not working in jQuery? How to use JQuery with ReactJS $(...).datepicker is not a function - JQuery - Bootstrap remove first element from array and return the array minus the first element How to use a jQuery plugin inside Vue Uncaught SyntaxError: Invalid or unexpected token jquery 3.0 url.indexOf error How to redirect page after click on Ok button on sweet alert? Content Security Policy: The page's settings blocked the loading of a resource Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document' Checkbox value true/false vue.js 'document.getElementById' shorthand Removing legend on charts with chart.js v2

Questions with jquery-plugins tag:

How to use a jQuery plugin inside Vue How add spaces between Slick carousel item Bootstrap carousel multiple frames at once Can someone explain how to implement the jQuery File Upload plugin? Correct way to integrate jQuery plugins in AngularJS Call Jquery function Twitter bootstrap remote modal shows same content every time Jquery Chosen plugin - dynamically populate list by Ajax How to show all rows by default in JQuery DataTable Change Placeholder Text using jQuery How to scroll up or down the page to an anchor using jQuery? Horizontal swipe slider with jQuery and touch devices support? Get query string parameters url values with jQuery / Javascript (querystring) Jquery date picker z-index issue jQuery UI tabs. How to select a tab based on its id not based on index Set width of a "Position: fixed" div relative to parent div Compress images on client side before uploading JQuery show/hide when hover javascript compare strings without being case sensitive jQuery multiselect drop down menu Making custom right-click context menus for my web-app jQuery Scroll To bottom of the page How can I display a tooltip on an HTML "option" tag? How to sort by Date with DataTables jquery plugin? How to move child element from one parent to another using jQuery jQuery counter to count up to a target number How to disable mouse scroll wheel scaling with Google Maps API What's the easiest way to call a function every 5 seconds in jQuery? jQuery Combobox/select autocomplete? jQuery: How can I show an image popup onclick of the thumbnail? Pie chart with jQuery How to change Jquery UI Slider handle How to create a jQuery plugin with methods? jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox JQuery to load Javascript file dynamically How to launch jQuery Fancybox on page load? How can I check if a jQuery plugin is loaded? Using jQuery, Restricting File Size Before Uploading Parse RSS with jQuery

Questions with webpack tag:

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 Support for the experimental syntax 'classProperties' isn't currently enabled npx command not found where is create-react-app webpack config and files? How can I go back/route-back on vue-router? webpack: Module not found: Error: Can't resolve (with relative path) Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src' The create-react-app imports restriction outside of src directory How to import image (.svg, .png ) in a React Component How to include css files in Vue 2 I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely How to import functions from different js file in a Vue+webpack+vue-loader project How to Install Font Awesome in Laravel Mix Field 'browser' doesn't contain a valid alias configuration Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema How to create multiple page app using react How to add fonts to create-react-app based projects? How to determine the installed webpack version Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type How to decrease prod bundle size? How to use Google fonts in React.js? How to include bootstrap css and js in reactjs app? Angular 2 : No NgModule metadata found angular-cli where is webpack.config.js file - new angular6 does not support ng eject How to add font-awesome to Angular 2 + CLI project webpack command not working Import JavaScript file and call functions using webpack, ES6, ReactJS Getting Unexpected Token Export How to use a jQuery plugin inside Vue 'import' and 'export' may only appear at the top level How to load image files with webpack file-loader Define global variable with webpack Static image src in Vue.js template Correct path for img on React.js How to bundle an Angular app for production Add Favicon with React and Webpack Angular 2: import external js file into component No 'Access-Control-Allow-Origin' header in Angular 2 app How to create multiple output paths in Webpack config webpack is not recognized as a internal or external command,operable program or batch file NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack Webpack how to build production code and how to use it React-Native: Module AppRegistry is not a registered callable module Webpack "OTS parsing error" loading fonts ES6 exporting/importing in index file How to import and export components using React + ES6 + webpack? ES6 modules implementation, how to load a json file "You may need an appropriate loader to handle this file type" with Webpack and Babel babel-loader jsx SyntaxError: Unexpected token How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

Questions with vue.js tag:

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Center content vertically on Vuetify Vue.js get selected option on @change Using Environment Variables with Vue.js did you register the component correctly? For recursive components, make sure to provide the "name" option Vue 'export default' vs 'new Vue' How can I go back/route-back on vue-router? Change the default base url for axios How to reference static assets within vue javascript How to change port number in vue-cli project Vuejs: Event on route change Vuex - Computed property "name" was assigned to but it has no setter Vuex - passing multiple parameters to mutation How to VueJS router-link active style How to use img src in vue.js? How to listen to the window scroll event in a VueJS component? How to acces external json file objects in vue.js app Difference between @click and v-on:click Vuejs How to import and use image in a Vue single file component? How to add external JS scripts to VueJS Components Vue JS mounted() Vue js error: Component template should contain exactly one root element Vue Js - Loop via v-for X times (in a range) How to listen for 'props' changes How can I set selected option selected in vue.js 2? How to include css files in Vue 2 How to pass a parameter to Vue @click event handler vue.js 2 how to watch store values from vuex Vue.js: Conditional class style binding How do I format currencies in a Vue component? Handling Enter Key in Vue.js Which command do I use to generate the build of a Vue app? [Vue warn]: Property or method is not defined on the instance but referenced during render VueJS conditionally add an attribute for an element Vuejs and Vue.set(), update array How to call function on child component on parent events How to use forEach in vueJs? VueJs get url query Vue.js—Difference between v-model and v-bind How to implement debounce in Vue2? Vue.js - How to properly watch for nested data Vue template or render function not defined yet I am using neither? Clearing input in vuejs form Vue v-on:click does not work on component How to add and remove item from array in components in Vue 2 Do we have router.reload in vue-router? Vue - Deep watching an array of objects and calculating the change? Setting a checkbox as checked with Vue.js How to access to a child method from the parent in vue.js Passing event and argument to v-on in Vue.js