How to share client side and server side js code?

I am using node js and have written some code which I initially duplicated from the a client side service (in angular js). Clearly this is the not the right way.

So how do you share code?

In Node js the fundamental building block is a module and anything in a module (functions, classes, class methods) are visible to everything inside that module which is inside a file. Now to expose or export functions etc we use module.exports.

Now a module can be written a number of ways, one of them is by using the javascript design pattern IIFE (immediately-invoked function expression).

Using an IIFE, I can define the exports object to be whatever I want. On the client side it will not be defined, so I can pass a simple object for exports and the execution of function will just attach the functions to this object. For the server side exports is the module system exports.

So, using an IIFE, we write the code as follows:

(function(exports){

exports.someSharedMethod = function(){
// code here will be shared
};

}(typeof exports === 'undefined' ? this.utilities = {} : exports));

On the server side:

var share = require('./utilities.js');
utilities.someSharedMethod();

And on the client side the file will be loaded via a script tag, so ‘this’ will be the windows object and the code is called as:

utilities.someSharedMethod();
Show your support

Clapping shows how much you appreciated Shamresh Khan’s story.