how to get `jQuery` as a function (not as a Module symbol) after ES6 style `import * as jQuery from “./js/jquery.js”;`

梦想的初衷 提交于 2019-12-13 11:27:43

问题


I'm experimenting with native ES6 modules support in Chrome. jQuery is not es6 module (no export) - I know. Still, trying to understand what does it mean for us.

This works without errors:

 <script type="module">
        import * as jQuery from "./js/jquery.js";
        window.console.log(jQuery);
 </script>

But of course jQuery thereis not a function but a Module symbol. The question is: is it possible to extract jQuery/$ function from jQuery module? When there are no exports defined on module?

So do we have a method to extract not exported function from Module in Chrome (as we have it e.g. in browserfy)?

P.S. I have made an stupid error ("as jQuery" <-> "as jQyery") but it changes nothing, it is only alias name.


回答1:


This:

 <script type="module">
        import "./js/jquery.js";
        window.console.log(window.$);
 </script>

creates jQuery on window as "side effect". JQuery code

( 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
});

There is some specific in this and the same behaviour can't be expected from all "legacy" scripts.

What is interesting next also works (my explaination: because of "fetching first rule")

 <script type="module">
        window.console.log(window.$); // also works and will return $ function even if import is declared bellow
        import "./js/jquery.js";
 </script>

Syntax import "module-name" described there https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Google article: https://developers.google.com/web/fundamentals/primers/modules

Also this loads jquery ONLY ONCE (and execute it ONLY ONCE):

    <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>

This is important feature that can be used in development.

P.S.

This works also but has its trap:

 <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">


来源:https://stackoverflow.com/questions/51922739/how-to-get-jquery-as-a-function-not-as-a-module-symbol-after-es6-style-impo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!