Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a script is running as a ES6 module (so that it can `export`), in Javascript?

I'd like to make a Javascript file that

  • exports its content (e.g. a class) if it can export (e.g. it has been loaded with <script type="module">)
  • and otherwise, assigns its content into the global variable such as window and global.

For example, let's assume such a file print.js.

Case A

One can use it like:

<script type="module">
    import print_things from "./print.js";
    print_things("Javascript innovation");
</script>

Case B

or,

<script src="./print.js"></script>
<script>
    print_things("Hmmmmmmm.");
</script>

Currently, using export makes the script throw an error in Case B: Uncaught SyntaxError: Unexpected token export. So it has to know whether export is available on the environment whereon it runs, in order to support the both use cases. How do I do this?

like image 671
Константин Ван Avatar asked Oct 28 '22 20:10

Константин Ван


2 Answers

Check out UMD (universal module definition). Namely, this example

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['exports', 'b'], function (exports, b) {
            factory((root.commonJsStrictGlobal = exports), b);
        });
    } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
        // CommonJS
        factory(exports, require('b'));
    } else {
        // Browser globals
        factory((root.commonJsStrictGlobal = {}), root.b);
    }
}(typeof self !== 'undefined' ? self : this, function (exports, b) {
    // Use b in some fashion.

    // attach properties to the exports object to define
    // the exported module properties.
    exports.action = function () {};
}));
like image 113
xavdid Avatar answered Nov 07 '22 18:11

xavdid


Browsers that understand type=module should ignore scripts with a nomodule attribute. This means you can serve a module tree to module-supporting browsers while providing a fall-back to other browsers.

<script type="module" src="module.js"></script>
<script nomodule src="fallback.js"></script>
like image 27
xjmdoo Avatar answered Nov 07 '22 19:11

xjmdoo