How to share code between Node.js and the browser?


Sharing code between the backend and front end of a full-stack application can be a challenging task. However, it's essential for building maintainable and scalable applications. By sharing code, we can avoid code duplication, reduce development time, and maintain consistency across our applications.

In this tutorial, we'll explore different techniques for sharing code between Node.js and the browser and learn how to choose the best approach for our project.

Techniques for Sharing Code Between Node.js and the Browser

Users can follow the approaches below to share code between node.js and the browser −

CommonJS Modules

CommonJS modules are a widely used and simple way to organize and share code in Node.js. Many Node.js packages are built using CommonJS modules because they're easy to use.

However, they don't work in the browser by default. To use CommonJS modules in the browser, we must use a tool like Browserify or Webpack. These tools can create a single JavaScript file that works in Node.js and the browser. Depending on the target environment, they can also convert our code from CommonJS to ES modules or vice versa.

If we're building a Node.js application and want to reuse some of our server-side code in the browser, CommonJS modules are a good choice.

ES Modules

ES modules are a modern and native way to organize and share code in both web browsers and Node.js. They are simple to use, and many modern front-end frameworks, such as React and Vue.js, support ES modules out of the box

We can use a package manager such as npm or Yarn to share code between Node.js and the browser. We can publish our code as a package and install it in both environments using the package manager.

ES modules are an excellent choice if we want to use a modern and standardized way to organize and share code between the backend and front end of our application.

Universal JavaScript

Universal JavaScript, also known as isomorphic JavaScript, allows us to write code that runs on both the server and the client. This can help improve performance, reduce page load times, and enhance SEO.

Universal JavaScript requires a lot of upfront configuration and can be complex to set up. Also, some libraries and APIs may not work the same way on the server and the client, leading to unexpected bugs.

It is a good choice if we need to build a highly performant and scalable application with server-side rendering and want to share as much code as possible between the backend and frontend.

By understanding these three approaches, users can choose the one that best fits their project requirements and development preferences.

Using Webpack to Share Node.js Code with the Browser

A build tool like Webpack is a powerful way to share code between Node.js and the browser. Users can follow the steps below to share code between node.js and the browser using Webpack −

Step 1 − First, we need to install Webpack on our machine.

npm install --save-dev webpack webpack-cli 

Step 2 − Next, we need to create a Webpack configuration file that specifies how our code should be bundled. Here's a simple example of what the file might look like:

module.exports = {
   entry: './src/index.js',
   output: {
      filename: 'bundle.js',
      path: __dirname + '/dist'
   }
}; 

Step 3 − After that, we can write our code as we normally would in Node.js or the browser.

Step 4 − Now, we need to bundle our code using the following command −

npx webpack --mode=development 

Step 5 − Finally, we can use the bundle in our Node.js or browser application by including it in our HTML file or by requiring it in our Node.js code.

For example, if we're using the default configuration from step 2, we can include the bundle in our HTML file like this −

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <title> My App </title>
   </head>
   <body>
      <script src = "dist/bundle.js"> </script>
   </body>
</html>

Example

This example demonstrates how to define and export functions for both Node.js and the browser using a universal JavaScript approach. In the myLibrary.js file, we define two functions, greet() and goodbye(), which can be used in both Node.js and browser environments. The code checks whether the module exists and exports the functions for Node.js, while exporting them to the window object for the browser.

In the index.js file, we import the myLibrary.js module using the require() function and then call the exported function goodbye() with a parameter.

In the index.html file, we include the myLibrary.js file as a script tag and then call the exported function greet() with a parameter using a script tag.

In this way, we can create a versatile and reusable codebase that can be used in both Node.js and browser environments, and the code will work correctly in each environment.

myLibrary.js

if (typeof module !== 'undefined' && module.exports) {
   
   // code for Node.js 
   module.exports = {
      
      // exported functions or objects for Node.js
      greet: function(name) {
         console.log('Hello, ' + name + '!');
      },
      goodbye: function(name) {
         console.log('Goodbye, ' + name + '!');
      }
   };
} else {
   
   // code for the browser
   window.myLibrary = {
      
      // exported functions or objects for the browser
      greet: function(name) {
         alert('Hello, ' + name + '!');
      },
      goodbye: function(name) {
         alert('Goodbye, ' + name + '!');
      }
   };
}

index.js

const myLibrary = require('./myLibrary');
myLibrary.goodbye('Subham'); 

index.html

<html lang="en">
<head>
   <title> NodeJs & Browser </title> 
</head>
<body>
   <script src = "myLibrary.js" > </script>
   <script>
      myLibrary.greet('Subham');
   </script>
</body>
</html>

Output

In this tutorial, users learned different techniques for sharing code between Node.js and the browser, including CommonJS Modules, ES Modules, and Universal JavaScript. Each approach has it’s strengths and weaknesses, and the choice will depend on the project requirements and development preferences.

By following the steps mentioned in this tutorial, users can create a Webpack configuration file that specifies how their code should be bundled, allowing them to write their code as they normally would in Node.js or the browser. We also saw an example of how to define exported functions for both Node.js and the browser using a universal JavaScript approach.

Updated on: 07-Mar-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements