Javascript – Proper import and export for NodeJS and the browser

The library should be reused for both the browser and the runtime environment of the node. This code will be published so that a code review can be performed to make it better and clearer.

question: To elegantly create a library that can be used on both platforms, the browser landscape and the NodeJS runtime environment.

The subsequent implementation takes care of it, but looks for opportunities for improvement.


Import

NodeJS convenience_product.js

let MyLib;

// import for either browser and the nodeJS
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    MyLib = require("../dist/mylib");
} else {
    MyLib = window.MyLib; 
}

class ConvenienceProduct extends MyLib.Product {

    constructor() {
        console.log("Hello ConvenienceProduct");
    }
}

browser index.html


    
    


export

nodeJS + Browser dist / mylib.js

"use strict";

(() => {  // using IIFE to avoid polluting browser namespace

    /** @class MyLib.Product **/ // this helps in code hinting
    class Product {
    }

    let MyLib = {
        Product: Product
    }

    if (typeof window !== "undefined") {
         window.MyLib = MyLib;
    } else {
         module.exports = MyLib;
    }

})();