Javascript – How to import jQuery from npm package using ES6 only

javascriptjquerynpm

I installed jQuery with npm -install jquery and it created a node_modules folder in my project with jquery in it. But when I try to import it using ES6 import it gives me an error.

I don't want to use Webpack or require() and have to compile it… anything else just plain vanilla ES6.

I'm always gettting this error

Uncaught SyntaxError: The requested module
'./node_modules/jquery/dist/jquery.min.js' does not provide an export
named '$'

or

Uncaught SyntaxError: The requested module
'./node_modules/jquery/src/jquery.js' does not provide an export named
'$'

Project structure

.
├── index.html
├── app.js
├── node_modules/
│   ├── jquery/
│   │   ├── dist/
│   │   │   ├── jquery.js
│   │   │   ├── jquery.min.js
│   │   ├── src/
│   │   │   ├── jquery.js
└── package.json

app.js

import { $ } from './node_modules/jquery/dist/jquery.min.js'; // <-- does not work
import { $ } from './node_modules/jquery/src/jquery.js'; // <-- does not work
window.$ = $;

$('body').css('background-color', 'red')

Best Answer

Try npm install jquery and then import $ from "jquery".