[英]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.