jqueryvue.jswebpackvuejs3

How to import jQuery into $ in a Vue.js 3 / Vite application


I am trying to include jQuery in a Vue.js 3 project, using Vite (https://github.com/vitejs/vite).

I include jQuery in my package.json dependencies:

  "dependencies": {
    "@types/jquery": "^3.5.0",
    "jquery": "^3.5.1",
    "vue": "^3.0.0-rc.1"
  },

I import it in Vite's skeleton's main.js, at the first line:

import * as $ from "jquery";

But this doesn't actually import the jQuery object into $ (it imports something else).

However, if I change it to:

import * as jqueryExports from "jquery";
...
window.$ = jqueryExports.default;

Then everything works correctly.

I'm pretty sure this is not the intended way. Also, I suspect that this issue is not Vite-specific, but I haven't tried it with Webpack.

What is the correct way to import jQuery?


Solution

  • Did you try like this:

    import $ from "jquery";
    

    or try to simply load it in the header before vuejs

    <script  src="https://code.jquery.com/jquery-3.5.1.min.js"  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="  crossorigin="anonymous"></script>