'jQuery is not defined' when use ES6 import

▼魔方 西西 提交于 2019-11-28 03:27:42

问题


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'.


回答1:


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.



来源:https://stackoverflow.com/questions/35358625/jquery-is-not-defined-when-use-es6-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!