Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Jquery to Vue-Cli 3

I'm currently trying to add Jquery to my vue-cli project. I am aware of the missbehaviour it can produce, but anyway; Since there is no build/webpack.base.conf.js anymore I tried editing vue.config.js by adding:

 module.exports {
    ...
    chainWebpack: config => {
    config.plugin('define').tap(definitions => {
      definitions[0] = Object.assign(definitions[0], {
        $: 'jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery',
        jQuery: 'jquery',
        _: 'lodash'
      })
      return definitions
    })
  }
   ...
 }

or

const webpack = require('webpack')

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

Both options don't seem to work. With #1 nothing seems to happen, with #2 I get the compile error; "plugins" is not allowed or 'ProvidePlugin' is unresolved and when I try to import jQuery directly in main.js and define the $ operator, jquery stays undefinded when I try to use it.

Big thank you in advance!

like image 335
nonNumericalFloat Avatar asked Nov 17 '18 20:11

nonNumericalFloat


People also ask

Can we use jQuery in Vue?

Finally, we can now install and use jQuery in Vue. I believe using jQuery in your application will probably save a lot of time for you. But, it might have performance issues. So, I recommend using vue packages that solve the same issue.

Does Vue CLI support Vue 3?

Vue CLI is now in maintenance mode. For new projects, please use create-vue to scaffold Vite-based projects. create-vue supports both Vue 2 and Vue 3.

Can Vue replace jQuery?

Although you can replace jQuery with Vue, you'll need to change your mindset about how to solve Web development problems.


1 Answers

Solved it by adding to main.js

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

That did it for me and jQuery is now available globally.

Another approach would be;

Vue.use({
install: function(Vue, options){
    Vue.prototype.$jQuery = require('jquery'); // you'll have this.$jQuery anywhere in your vue project
    }
});

I hope this will help someone stumbling over the same problem in the future. If you still can't figure it out, check this question or have a look at the documentation.

edit: make sure you ran npm install jquery.

like image 175
nonNumericalFloat Avatar answered Sep 28 '22 13:09

nonNumericalFloat