How to Import jQuery in ES6 Modules
This guide covers the correct syntax for importing jQuery within modern JavaScript environments utilizing ES6 modules (ECMAScript 2015+). You will learn the standard import statements, how to make jQuery globally accessible for legacy plugins, and how to properly configure the package in your build tools.
Prerequisites
Before using ES6 imports, ensure that the jQuery package is installed in your project:
npm install jqueryStandard ES6 Import Syntax
The standard way to import jQuery into an ES6 module is by using the
default import syntax. You can assign it to $ or
jQuery:
import $ from 'jquery';
// You can now use jQuery as usual
$(document).ready(() => {
console.log('DOM is fully loaded with jQuery!');
});Alternatively, you can import it under the jQuery
identifier:
import jQuery from 'jquery';
jQuery('button').on('click', () => {
alert('Button clicked!');
});Namespace Import Syntax
In some environments or build configurations (such as certain TypeScript or Rollup setups), you may need to import the entire module namespace:
import * as $ from 'jquery';Making jQuery Global
Many legacy jQuery plugins expect the $ and
jQuery variables to exist on the global window
object. By default, ES6 module imports scope variables locally to the
module. To expose jQuery globally across your application, attach it to
window:
import $ from 'jquery';
window.$ = $;
window.jQuery = $;TypeScript Support
If you are using TypeScript with ES6 modules, install the corresponding type definitions so the compiler recognizes jQuery syntax:
npm install --save-dev @types/jqueryOnce installed, use the standard import syntax:
import $ from 'jquery';