In this article, we will explore how to write JavaScript modules that can be used by both the client-side and the server-side applications. We have a small web application with a JavaScript client (running in the browser) and a Node.js server communicating with it. And we have a function getFrequency() which is to be used by both server and client to get the frequency of characters in a given string. We want to create a single set of methods which can facilitate the task at both the ends. Approach: Writing code for client-side (running in the browser) differs a lot from server-side Node.js application. In client-side we mainly deal with DOM or web APIs like cookies, but these things don’t exist in Node. Other reasons why we cannot use node modules at the client side is that the node uses the CommonJS module system while the browser uses standard ES Modules which has different syntax. In node, we use module.exports to expose functionality or property. However, this will break in the browser, as the browser cannot recognize exports. So, to make it work, we check if exports is defined, if not then we create a sensible object for exporting functions. In the browser, this can be achieved by creating a global variable that has the same name as that of the module. The structure of the module will look something like as follows: sampleModule.js
javascript
// Checking if exports is defined
if(typeofexports === 'undefined'){
varexports = this['sampleModule'] = {};
}
// The code define the functions,
// variables or object to expose as
// exports.variableName
// exports.functionName
// exports.ObjectName
// Function not to expose
functionnotToExport(){ }
// Function to be exposed
exports.test(){ }
The above format has a problem that anything we define in sampleModule.js but not exported will be available to the browser, i.e. both the function notToExport() and test() will work outside this file. So, to overcome this we wrap the module in a closure. sampleModule.js