使用 ES6 导入时“未定义 jQuery"

我的代码:

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

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

我在浏览器控制台中有未定义 jQuery".怎么了?我可以在此类的方法中使用 jQuery 作为 $,但不能使用名称 'jQuery'.

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

推荐答案

根据此评论并将其应用于您的案例,当您这样做时:

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.

问题在于,当您执行 import $ ...import jQuery ... 然后 import 'owlCarousel'(其中依赖于 jQuery),这些都是在之前评估的,即使你在导入 jquery 之后立即声明 window.jQuery = jquery.这是 ES6 模块语义不同于 CommonJS 的 require 的方式之一.

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:

创建文件jquery-global.js

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

然后将其导入主文件:

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

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

这样可以确保在加载 owlCarousel 之前定义了全局 jQuery.

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

相关文章