0

I'm trying to import jQuery using ES6, and, most importantly, I'm running the code using babel-node (cli).

I've read a question, but the solution reported there doesn't seem to work: I tried

npm i --save jquery

and then

import {$,jQuery} from 'jquery';

console.log($);

But I get undefined logged to the console, and I cannot use jQuery.

How should I import $?

I also tried

import $ from 'jquery';

as suggested from @Jai and reported on the npm manual, but even though I obtain "[Function"] as the result of console.log($), $.getJSON("www.google.com") returns me TypeError: _jquery2.default.getJSON is not a function.

This is true only running the code from babel-node (cli), if I run the code from the browser loading the generated bundle it works.

cdarwin
  • 4,141
  • 9
  • 42
  • 66
  • Check this: https://stackoverflow.com/questions/34338411/how-to-import-jquery-using-es6-syntax – Majid Akbari Aug 13 '18 at 14:50
  • Have you tried the actual syntax from the question? `import * as $ from 'jquery';` If you write `import { $, JQuery }`, you try to destructure the object the jquery file returns, which isn't correct I think. Also, $ and JQuery are the same function. – Shilly Aug 13 '18 at 14:51
  • Checkout the npm package [how to import jquery](https://www.npmjs.com/package/jquery#babel) – Jai Aug 13 '18 at 14:52
  • @Shilly Trying import * as $ from 'jquery'; and then using $.getJSON("http://www.google.com"); gives me TypeError: $.getJSON is not a function – cdarwin Aug 13 '18 at 15:06
  • Which version of jQuery are you using? If you are using jQuery slim $.getJSON is not part of the interface which is why you'd see that error. It doesn't package $.ajax or the helper methods. – dysfunc Aug 13 '18 at 15:35
  • @dysfunc npm tells me jquery is 3.3.1, and I think it is the full version of the library. I also tried $.get but it doesn't work either. – cdarwin Aug 13 '18 at 15:39
  • what do you have in your package.json for jQuery? – dysfunc Aug 13 '18 at 15:42
  • @dysfunc "jquery": "^3.3.1". However I've just tried running the code from the browser using the generated bundle and it works, it doesn't work running it from cli with babel-node, maybe I'll update my question – cdarwin Aug 13 '18 at 15:45

1 Answers1

2

I suggest you try using the code below

import $ from 'jquery';

or

import jQuery from 'jquery';

Xixis
  • 881
  • 6
  • 8
  • I tried the first solution. console.log says "[Function]", but $.getJSON("http://www.google.com"); gives me TypeError: _jquery2.default.getJSON is not a function – cdarwin Aug 13 '18 at 15:00