2

I'm trying to practice using ES6 syntax, and I wanted to try using ES6 with jQuery and Webpack. I read a StackOverflow post illustrating how, and down below there was a comment saying why not just do

import {$, jQuery} from 'jquery'

I tried, and I'm getting an error saying Uncaught TypeError: (0 , r.$) is not a function. When I simply separate the two using two import statements, the error goes away. Any idea why? Is the one line import statement invalid? If so, how come?

Community
  • 1
  • 1
Sticky
  • 3,671
  • 5
  • 34
  • 58
  • Have you tried using webpack ProvidePlugin? : `new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" })` – Andrés Andrade Dec 23 '16 at 22:14
  • jquery only exports $... the answer you reference is actually wrong in his example `$` and `jquery` are the same thing – Maxwelll Dec 23 '16 at 22:14
  • Try doing `import $, jQuery from 'jquery'` so that it gives the default import two names. – 4castle Dec 23 '16 at 22:18
  • `import $, * as jQuery from "jquery";`? Or if they are both defaults `import $, jQuery from "jquery";`? – Andrew Li Dec 23 '16 at 22:19
  • @AndrésAndrade what do you mean? I've only been learning React with Webpack so I'm unaware of the ProvidePlugin feature. Would that go in my `webpack.config.js` file? @Maxwelll got it, thank you! @4castle @Andrew Li I can't do `import $, jQuery from 'jquery'` as that results in `unexpected token` error when compiling. I think the lesson learned here is that jquery only exports `$`. – Sticky Dec 23 '16 at 22:29
  • 1
    @Sticky Exactly. This way you can make a module available as a variable in every module so you don't have to import it every time https://webpack.github.io/docs/shimming-modules.html#plugin-provideplugin – Andrés Andrade Dec 23 '16 at 22:40
  • @AndrésAndrade oh awesome! thanks, I will take a look – Sticky Dec 23 '16 at 22:45

1 Answers1

3
import X from 'thing';

is short for

import {default as X} from 'thing';

which means if you want to import the default as both $ and jQuery, you need to do

import {default as $, default as jQuery} from 'jquery';

Note, jquery exports only $ and doing the above only aliases jquery as two different names. Also, be sure to checkout Webpack's ProvidePlugin feature.

Sticky
  • 3,671
  • 5
  • 34
  • 58
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • none of above worked for me.. ERROR Module .../node_modules/jquery/dist/jquery.js does not export default this works `import * as jQuery from 'jquery';` – Ritin Apr 23 '17 at 12:37
  • Perhaps you have something in your webpack config that is breaking that behavior? It definitely works. – loganfsmyth Apr 23 '17 at 16:26