[英]how to get `jQuery` as a function (not as a Module symbol) after ES6 style `import * as jQuery from "./js/jquery.js";`
我正在嘗試在 Chrome 中使用原生 ES6 模塊支持。 jQuery 不是 es6 模塊(無導出)——我知道。 盡管如此,還是試圖了解這對我們意味着什么。
這工作沒有錯誤:
<script type="module">
import * as jQuery from "./js/jquery.js";
window.console.log(jQuery);
</script>
但是當然jQuery
不是一個函數而是一個Module
符號。 問題是:是否可以從 jQuery 模塊中提取 jQuery/$ 函數? 當模塊上沒有定義導出時?
那么我們是否有一種方法可以從 Chrome 中的模塊中提取未導出的函數(就像我們在 browserfy 中擁有的那樣)?
PS我犯了一個愚蠢的錯誤(“as jQuery”<->“as jQyery”)但它什么也沒改變,它只是別名。
這個:
<script type="module">
import "./js/jquery.js";
window.console.log(window.$);
</script>
在窗口上創建 jQuery 作為“副作用”。 查詢代碼
( function( global, factory ) {
"use strict";
if (typeof module === "object" && typeof module.exports === "object") {
// ...
} else {
// we are there when loading as ES6 native module
factory( global );
}
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// ... jquery code
});
這有一些特定的,並且不能從所有“遺留”腳本中期望相同的行為。
接下來有趣的事情也有效(我的解釋:因為“獲取第一條規則”)
<script type="module">
window.console.log(window.$); // also works and will return $ function even if import is declared bellow
import "./js/jquery.js";
</script>
語法import "module-name"
在那里描述https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
谷歌文章: https : //developers.google.com/web/fundamentals/primers/modules
這也只加載 jquery 一次(並且只執行一次):
<script type="module">
import("./js/jquery.js").then(
function(){
window.console.log("inline 2a = " + window.$);
}
);
</script>
<script type="module">
import("./js/jquery.js").then(
function(){
window.console.log("inline 2b = " + window.$);
}
);
</script>
這是可以在開發中使用的重要功能。
聚苯乙烯
這也有效,但有其陷阱:
<script type="module">
import * as jQuery from "./js/jquery.js"
window.console.log(jQuery); // returns Module
window.console.log(window.jQuery); // returns jQuery function
</script type="module">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.