0
\$\begingroup\$

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

})();
\$\endgroup\$
  • \$\begingroup\$ how can I improve this question? \$\endgroup\$ – AppDeveloper Nov 10 at 22:52
  • 1
    \$\begingroup\$ Describing the purpose of the code, presenting it to reviewers, would probably help ;-) \$\endgroup\$ – Mathieu Guindon Nov 11 at 0:04
  • \$\begingroup\$ while implementation of the class doesn't matter and remains empty, the purpose of the code is to build a library that functions in both the browser as well as the nodejs runtime \$\endgroup\$ – AppDeveloper Nov 11 at 0:18
  • \$\begingroup\$ Implementation always matters on Code Review, please see the help center. \$\endgroup\$ – Mast Nov 11 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.