The Library is meant to be re-used for both the browser and the nodejs runtime environment, publishing this code for a code review to make it better and concise.
Question: How to build a library in an elegant way that's usable on both platforms, Browser Landscape and NodeJS runtime environment.
Following implementation takes care of that, but seeking for any room 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
<head>
<script src="../dist/mylib.js"></script>
<script src="convenience_product.js"></script>
</head>
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;
}
})();