Understanding module systems in JavaScript and Running JavaScript: A Complete Guide
In this guide, we'll explore how to make sure your JavaScript files run smoothly in the browser, covering various techniques and best practices.
JavaScript is a versatile programming language that runs both on the server and in the browser. However, not all JavaScript code runs directly in the browser, especially if you're used to working with server-side environments like Node.js. In this guide, we'll explore how to make sure your JavaScript files run smoothly in the browser, covering various techniques and best practices.
1. Understanding Module Systems in JavaScript
JavaScript supports two primary module systems:
a) CommonJS (CJS)
CommonJS is the default module system in Node.js.
Uses
require()andmodule.exports.Synchronous module loading, making it suitable for server-side applications.
Not natively supported in browsers.
Example: math.js
function add(a, b) {
return a + b;
}
module.exports = add;main.js
const add = require('./math');
console.log(add(2, 3));To run this in Node.js:
node main.jsb) ES Modules (ESM)
Introduced in ECMAScript 2015 (ES6).
Uses
importandexportstatements.Asynchronous loading, suitable for both client and server.
Supported natively in modern browsers.
Example: math.mjs
export function add(a, b) {
return a + b;
}main.mjs
import { add } from './math.mjs';
console.log(add(2, 3));To run this in Node.js:
node --experimental-modules main.mjsDifferences Between CommonJS and ESM
FeatureCommonJSES Modules | ||
Syntax | require/module.exports | import/export |
Loading Type | Synchronous | Asynchronous |
Browser Support | No | Yes |
Usage in Node.js | Default | Via |
2. Running JavaScript in the Browser
To make sure your JavaScript files run properly in the browser, follow these steps:
a) Using ES Modules (Recommended)
Modern browsers support ES Modules out of the box. To take advantage of this feature, follow these steps:
File Structure:
project/
├── index.html
├── main.js
└── utils.jsutils.js
// Exporting a utility function
export function greet(name) {
return `Hello, ${name}!`;
}main.js
// Importing the function from utils.js
import { greet } from './utils.js';
console.log(greet('Sajit'));index.html
<!DOCTYPE html>
<html>
<head>
<title>Running JS in the Browser</title>
</head>
<body>
<script type="module" src="./main.js"></script>
</body>
</html>Running the Project
To run the project, you need to use a local server because browsers enforce strict CORS policies when using modules.
Using Python HTTP Server (Quick Method)
python -m http.server 3000Visit http://localhost:3000 to see the output in your browser’s console.
Using Node.js HTTP Server
npm install -g http-server
http-server -p 3000Visit http://localhost:3000.
3. Using Bundlers for CommonJS
If your project uses CommonJS syntax, you need to bundle your code. The most common tools are Webpack, Parcel, and Rollup.
Example with Webpack
Install Webpack:
npm init -y
npm install webpack webpack-cli --save-devwebpack.config.js
const path = require('path');
module.exports = {
entry: './main.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
mode: 'development',
};main.js
const greet = require('./utils');
console.log(greet('Sajit'));utils.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = greet;Running Webpack
npx webpackThis will generate a dist/bundle.js file that you can include in your HTML file:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Bundled JavaScript</title>
</head>
<body>
<script src="./dist/bundle.js"></script>
</body>
</html>4. Summary
Use ES Modules for modern, native browser support.
Serve your files through a local server to avoid CORS issues.
Use bundlers like Webpack to convert CommonJS into browser-compatible code.
Understand the differences between CommonJS and ES Modules to choose the right approach based on your project.