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">)window and global.For example, let's assume such a file print.js.
One can use it like:
<script type="module">
    import print_things from "./print.js";
    print_things("Javascript innovation");
</script>
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?
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 () {};
}));
                        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>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With