How do I globally declare jQuery inside a Vue-CLI 3 project?

Viewed 2231

I have seen a lot of questions about this on SO and elsewhere, but so far I had no luck.

For a bit of context, I built a SPA website on a Vue project I created with an "old" command. I don't remember which one but it looked like the following:

vue init webpack <my project>

I recently realized that Vue-CLI 3 would be way easier for me to maintain, keep updated and improve for various contextual reasons, so I installed @vue/cli, created a new project and started to copy/paste files from my old project to the new one.

The old project had a build directory with various webpack config files in it, and I needed jQuery set globally for a package I wanted to use, so I added the following to the "base" config of Webpack.

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

However, with the new project, all I have now as config file is babel.config.js and vue.config.js at the project's root, there are no build nor config directory.

I tried to set jQuery globally with the following lines inside my main.js file:

import jQuery from 'jquery'

window.$ = window.jQuery = jQuery
global.$ = global.jQuery = jQuery

But everytime I reload my page, I get the following message:

jQuery is not defined

So, so far, I use the CDN version of jQuery but I don't feel at ease with this solution.

How should I proceed with a Vue-CLI 3 project?

Thank you in advance

3 Answers

You can use Vue plugins. This allows you to add new property to every single component.

In main.js

import Vue from 'vue';
import jQuery from 'jquery';

Vue.use({
  install (V) {
    V.$jQuery = V.prototype.$jQuery = jQuery
  }
})

Then you can use jQuery everywhere in component.

In MyComponent.vue

import Vue from 'vue'

export default {
  mounted () {
    this.$jQuery('h1').text('Hello World')
    Vue.$jQuery('h1').text('Hello World')
  }
}

Even another js file.

In util.js

import Vue from 'vue'

Vue.$jQuery('h1').text('Hello World')

You could go on public/index.html and add the script tag to the body with the route to your jquery file or cdn. If you put it in a jquery folder in public it would look like:

<body>
    <div id="app"></div>
    <script type="text/javascript" src="/jquery/jquery-3.4.1.min.js"></script>
</body>

I am not sure if that's exactly what you want but it would make it available globally across your project.

If you are using Jquery plugins, you should do this in your main.js:

/*
* If using Jquery plugins they will expect to be available in the global namespace, 
* which isn’t the case when you import/require it. So manually assign jquery to 
* window. Use require instead of import because the imports are hoisted to the
* top of a file by the compiler, which would break VueJS code.
*/
const $ = require('jquery')
window.jQuery = window.$ = $;
Related