简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM