6
votes

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')
2
But wait. jQuery is a client-side library, are you trying to import it in Node? And then use it in Node with $('body').css()? What am I missing?Jeremy Thille
No, I just wanted to use npm as a package manager and include it in browser.Liga
So what's wrong with <script src="jquery.js"> ?Jeremy Thille
And try $ instead of { $ }.Nenad Vracar
Just import './node_modules/jquery/dist/jquery.min.js' works for me.Nenad Vracar

2 Answers

1
votes

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

0
votes

At the moment, this functionality is only beginning to be supported by browsers. Full implementation is provided in many transpilers such as TypeScript and Babel, and bundlers such as Webpack.

ES6 modules have been fully supported in Chrome since version 65 but it still throws errors if we try and use the import/export keywords to import or export modules in JavaScript files.

So what do you have to do to make ES6 modules work without Webpack/Browserify/Babel is to add next script tag in your index.html file:

<script type="module" src="ES6-Node.js"></script>