How to import jquery using ES6 syntax?
index.js
import {$,jQuery} from 'jquery';// export for others scripts to usewindow.$ = $;window.jQuery = jQuery;
First, as @nem suggested in comment, the import should be done from node_modules/
:
Well, importing from
dist/
doesn't make sense since that is your distribution folder with production ready app. Building your app should take what's insidenode_modules/
and add it to thedist/
folder, jQuery included.
Next, the glob –* as
– is wrong as I know what object I'm importing (e.g. jQuery
and $
), so a straigforward import statement will work.
Last you need to expose it to other scripts using the window.$ = $
.
Then, I import as both $
and jQuery
to cover all usages, browserify
remove import duplication, so no overhead here! ^o^y
Based on the solution of Édouard Lopez, but in two lines:
import jQuery from "jquery";window.$ = window.jQuery = jQuery;
You can create a module converter like below:
// jquery.module.jsimport 'https://code.jquery.com/jquery-3.6.0.min.js'export default window.jQuery.noConflict(true)
This will remove global variables introduced by jQuery and export jQuery object as default.
Then use it in your script:
// script.jsimport $ from "./jquery.module.js"; $(function(){ $('body').text('youpi!');});
Do not forget to load it as a module in your document:
<script type='module' src='./script.js'></script>