我的代码:
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 thenimport 'owlCarousel'
(which depends onjQuery
), these are evaluated before, even if you declarewindow.jQuery = jquery
right after importingjquery
. 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
全局。
关于javascript - 使用 ES6 导入时“未定义 jQuery”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35358625/