How to import jquery using ES6 syntax?

index.js

import {$,jQuery} from 'jquery';
// export for others scripts to use
window.$ = $;
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 inside node_modules/ and add it to the dist/ 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


You can create a module converter like below:

// jquery.module.js
import 'https://code.jquery.com/jquery-3.6.0.min.js'
export default window.jQuery.noConflict(true)

This will remove global variables introduced by jQuery (jQuery & $) and export jQuery object as default.

Then use it in your script:

// script.js
import $ 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>

http://plnkr.co/edit/a59ETj3Yo2PJ0Aqkxbeu?p=preview


Based on the solution of Édouard Lopez, but in two lines:

import jQuery from "jquery";
window.$ = window.jQuery = jQuery;