#39;jQuery is not defined#39; when use ES6 import(使用 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 thenimport 'owlCarousel'(which depends onjQuery), these are evaluated before, even if you declarewindow.jQuery = jqueryright after importingjquery. 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.
这篇关于使用 ES6 导入时“未定义 jQuery"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 ES6 导入时“未定义 jQuery"
基础教程推荐
- Bootstrap 模态出现在背景下 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
