javascript – 使用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’.

解决方法

根据 this comment并将其应用于您的案例,当您正在做:
import $from 'jquery'
import jQuery from 'jquery'

你实际上并没有使用命名导出.

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.

解决这个问题的一种方法是改为:

创建文件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全局.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...