問題描述
我的代碼:
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 = jquery
right 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"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!