Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'jQuery is not defined' when use ES6 import

My code:

import $ from 'jquery'
import jQuery from 'jquery'
import owlCarousel from '../../node_modules/owlcarousel/owl-carousel/owl.carousel'

class App {
    …
    _initSlider() {
        $("#partners-carousel").owlCarousel();
    }
}

I have 'jQuery is not defined' in browser console. What's wrong? I can use jQuery as $ in methods of this class, but not with name 'jQuery'.

like image 214
Serge Avatar asked Feb 12 '16 09:02

Serge


1 Answers

According to this comment and apply it to your case, when you're doing:

import $ from 'jquery'
import jQuery from 'jquery'

you aren't actually using a named export.

The problem is that when you do import $ ..., import jQuery ... and then import 'owlCarousel' (which depends on jQuery), these are evaluated before, even if you declare window.jQuery = jquery right after importing jquery. That's one of the ways ES6 module semantics differs from CommonJS' require.

One way to get around this is to instead do this:

Create file jquery-global.js

// jquery-global.js
import jquery from 'jquery';
window.jQuery = jquery;
window.$ = jquery;

then import it in you main file:

// main.js
import './jquery-global.js';
import 'owlCarousel' from '../../node_modules/owlcarousel/owl-carousel/owl.carousel'

class App {
  ...
  _initSlider() {
    $("#partners-carousel").owlCarousel();
  }
}

That way you make sure that the jQuery global is defined before owlCarousel is loaded.

like image 186
Egel Avatar answered Sep 28 '22 09:09

Egel