[javascript] How to import jquery using ES6 syntax?

I'm writing a new app using (JavaScript) ES6 syntax through babel transpiler and the preset-es2015 plugins, as well as semantic-ui for the style.

index.js

import * as stylesheet from '../assets/styles/app.scss';
import * as jquery2 from '../dist/scripts/jquery.min';
import * as jquery3 from '../node_modules/jquery/dist/jquery.min';

console.log($('my-app'));

index.html

<!DOCTYPE html>
<html lang="fr">
<head>
<body>
<script src="dist/app.js"></script>
</body>
</html>

Project structure

.
+-- app/
¦   +-- index.js
+-- assets/
+-- dist/
¦   +-- scripts/
¦   ¦   +-- jquery.min.js
+-- index.html
+-- node_modules/
¦   +-- jquery/
¦   ¦   +-- dist/
¦   ¦   ¦   +-- jquery.min.js
+-- package.json
+-- tests/

package.json

  …
  "scripts": {
    "build:app": "browserify -e ./app/index.js -o ./dist/app.js",
    "copy:jquery": "cpy 'node_modules/jquery/dist/jquery.min.js' ./dist/scripts/",
    …
  },
  "devDependencies": {
    "babel-core": "6.3.x",
    "babel-preset-es2015": "6.3.x",
    "babelify": "7.2.x",
    "cpy": "3.4.x",
    "npm-run-all": "1.4.x",
    "sassify": "0.9.x",
    "semantic-ui": "2.1.x",
    …
  },
  "browserify": {
    "transform": [
      [ "babelify", { "presets": [ "es2015"]}],
      [ "sassify", { "auto-inject": true}]
    ]
  }

Question

Using classic <script> tag to import jquery works fine, but I'm trying to use the ES6 syntax.

  • How do I import jquery to satisfy semantic-ui using ES6 import syntax?
  • Should I import from the node_modules/ directory or my dist/ (where I copy everything)?

This question is related to javascript jquery ecmascript-6 browserify semantic-ui

The answer is


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

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

The accepted answer did not work for me
note : using rollup js dont know if this answer belongs here
after
npm i --save jquery
in custom.js

import {$, jQuery} from 'jquery';

or

import {jQuery as $} from 'jquery';

i was getting error : Module ...node_modules/jquery/dist/jquery.js does not export jQuery
or
Module ...node_modules/jquery/dist/jquery.js does not export $
rollup.config.js

export default {
    entry: 'source/custom',
    dest: 'dist/custom.min.js',
    plugins: [
        inject({
            include: '**/*.js',
            exclude: 'node_modules/**',
            jQuery: 'jquery',
            // $: 'jquery'
        }),
        nodeResolve({
            jsnext: true,
        }),
        babel(),
        // uglify({}, minify),
    ],
    external: [],
    format: 'iife', //'cjs'
    moduleName: 'mycustom',
};

instead of rollup inject, tried

commonjs({
   namedExports: {
     // left-hand side can be an absolute path, a path
     // relative to the current directory, or the name
     // of a module in node_modules
     // 'node_modules/jquery/dist/jquery.js': [ '$' ]
     // 'node_modules/jquery/dist/jquery.js': [ 'jQuery' ]
        'jQuery': [ '$' ]
},
format: 'cjs' //'iife'
};

package.json

  "devDependencies": {
    "babel-cli": "^6.10.1",
    "babel-core": "^6.10.4",
    "babel-eslint": "6.1.0",
    "babel-loader": "^6.2.4",
    "babel-plugin-external-helpers": "6.18.0",
    "babel-preset-es2015": "^6.9.0",
    "babel-register": "6.9.0",
    "eslint": "2.12.0",
    "eslint-config-airbnb-base": "3.0.1",
    "eslint-plugin-import": "1.8.1",
    "rollup": "0.33.0",
    "rollup-plugin-babel": "2.6.1",
    "rollup-plugin-commonjs": "3.1.0",
    "rollup-plugin-inject": "^2.0.0",
    "rollup-plugin-node-resolve": "2.0.0",
    "rollup-plugin-uglify": "1.0.1",
    "uglify-js": "2.7.0"
  },
  "scripts": {
    "build": "rollup -c",
  },

This worked :
removed the rollup inject and commonjs plugins

import * as jQuery from 'jquery';

then in custom.js

$(function () {
        console.log('Hello jQuery');
});

I did not see this exact syntax posted yet, and it worked for me in an ES6/Webpack environment:

import $ from "jquery";

Taken directly from jQuery's NPM page. Hope this helps someone.


If it helps anyone, javascript import statements are hoisted. Thus, if a library has a dependency (eg bootstrap) on jquery in the global namespace (window), this will NOT work:

import {$,jQuery} from 'jquery';
window.$ = $;
window.jQuery = jQuery;
import 'bootstrap/dist/js/bootstrap.min';

This is because the import of bootstrap is hoisted and evaluated before jQuery is attached to window.

One way to get around this is to not import jQuery directly, but instead import a module which itself imports jQuery AND attaches it to the window.

import jQuery from './util/leaked-jquery';
import 'bootstrap/dist/js/bootstrap.min';

where leaked-jquery looks like

import {$,jQuery} from 'jquery';
window.$ = $;
window.jQuery = jQuery;
export default $;
export jQuery;

EG, https://github.com/craigmichaelmartin/weather-app--birch/blob/4d9f3b03719e0a2ea3fb5ddbbfc453a10e9843c6/javascript/util/leak_jquery.js


If you are not using any JS build tools/NPM, then you can directly include Jquery as:

import  'https://code.jquery.com/jquery-1.12.4.min.js';
const $ = window.$;

You may skip import(Line 1) if you already included jquery using script tag under head.


First of all, install and save them in package.json:

npm i --save jquery
npm i --save jquery-ui-dist

Secondly, add a alias in webpack configuration:

resolve: {
  root: [
    path.resolve(__dirname, '../node_modules'),
    path.resolve(__dirname, '../src'),
  ],
  alias: {
    'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
  },
  extensions: ['', '.js', '.json'],
}

It work for me with the last jquery(3.2.1) and jquery-ui(1.12.1).

See my blog for detail: http://code.tonytuan.org/2017/03/webpack-import-jquery-ui-in-es6-syntax.html


You can import like this

import("jquery").then((jQuery) => {
  window.$ = jQuery;
  window.jQuery = jQuery;
  import("bootstrap").then((_bs)=>{
    $(function() {});
  })
});

Pika is a CDN that takes care of providing module versions of popular packages

<script type='module'>
    import * as $ from 'https://cdn.skypack.dev/jquery';

    // use it!
    $('#myDev').on('click', alert);
</script>

Skypack is Pika, so you could also use: import * as $ from 'https://cdn.pika.dev/jquery@^3.5.1';


Import the entire JQuery's contents in the Global scope. This inserts $ into the current scope, containing all the exported bindings from the JQuery.

import * as $ from 'jquery';

Now the $ belongs to the window object.


My project stack is: ParcelJS + WordPress

WordPress got jQuery v1.12.4 itself and I have also import jQuery v3^ as module for other depending modules as well as bootstrap/js/dist/collapse, for example... Unfortunately, I can’t leave only one jQuery version due to other WordPress modular dependencies. And ofcourse there is conflict arises between two jquery version. Also keep in mind we got two modes for this project running Wordpress(Apache) / ParcelJS (NodeJS), witch make everything little bit difficulty. So at solution for this conflict was searching, sometimes the project broke on the left, sometimes on the right side. SO... My finall solution (I hope it so...) is:

    import $ from 'jquery'
    import 'popper.js'
    import 'bootstrap/js/dist/collapse'
    import 'bootstrap/js/dist/dropdown'
    import 'signalr'

    if (typeof window.$ === 'undefined') {
        window.$ = window.jQ = $.noConflict(true);
    }

    if (process) {
        if (typeof window.jQuery === 'undefined') {
            window.$ = window.jQuery = $.noConflict(true);
        }
    }

    jQ('#some-id').do('something...')    

    /* Other app code continuous below.......... */

I still didn’t understand how myself, but this method works. Errors and conflicts of two jQuery version no longer arise


webpack users, add the below to your plugins array.

let plugins = [
  // expose $ and jQuery to global scope.
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
];

import {jQuery as $} from 'jquery';

You can create a module converter like below:

// jquery.module.js
import 'https://code.jquery.com/jquery-3.3.1.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.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


If you are using Webpack 4, the answer is to use the ProvidePlugin. Their documentation specifically covers angular.js with jquery use case:

new webpack.ProvidePlugin({
  'window.jQuery': 'jquery'
});

The issue is that when using import syntax angular.js and jquery will always be imported before you have a chance to assign jquery to window.jQuery (import statements will always run first no matter where they are in the code!). This means that angular will always see window.jQuery as undefined until you use ProvidePlugin.


I wanted to use the alread-buildy jQuery (from jquery.org) and all the solutions mentioned here didn't work, how I fixed this issue was adding the following lines which should make it work on nearly every environment:

 export default  ( typeof module === 'object' && module.exports && typeof module.exports.noConflict === 'function' )
    ? module.exports.noConflict(true)
    : ( typeof window !== 'undefined' ? window : this ).jQuery.noConflict(true)

Import jquery (I installed with 'npm install [email protected]')

import 'jquery/jquery.js';

Put all your code that depends on jquery inside this method

+function ($) { 
    // your code
}(window.jQuery);

or declare variable $ after import

var $ = window.$

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ecmascript-6

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 where is create-react-app webpack config and files? Can (a== 1 && a ==2 && a==3) ever evaluate to true? How do I fix "Expected to return a value at the end of arrow function" warning? Enums in Javascript with ES6 Home does not contain an export named Home How to scroll to an element? How to update nested state properties in React eslint: error Parsing error: The keyword 'const' is reserved Node.js ES6 classes with require

Examples related to browserify

How to import jquery using ES6 syntax?

Examples related to semantic-ui

How to import jquery using ES6 syntax? Center div on the middle of screen