What is Module in javascript ES6?

In JavaScript ES6, a module is a way to organize code into reusable files with well-defined interfaces. It allows you to encapsulate functionality and variables, preventing them from polluting the global namespace. ES6 introduced a standardized module system that provides a cleaner and more organized approach to structuring and managing code.

Here are the key features of ES6 modules:

  1. File-Level Scope:
    Each module has its own file-level scope, meaning that variables and functions declared in a module are local to that module by default. They are not automatically exposed to the global scope, preventing naming conflicts.
  2. Export and Import Statements:
    Modules use the export statement to expose variables, functions, or classes, and the import statement to bring in functionality from other modules.
   // module1.js
   export const variable1 = 'Hello';
   export function greet(name) {
     return `${variable1}, ${name}!`;
   }

   // module2.js
   import { variable1, greet } from './module1.js';

   console.log(variable1);      // Output: Hello
   console.log(greet('John'));  // Output: Hello, John!
  1. Default Exports and Imports:
    In addition to named exports, modules can have a default export. This allows you to export a single value or function as the default export and import it without using curly braces.
   // module1.js
   const variable1 = 'Hello';
   export default variable1;

   // module2.js
   import greeting from './module1.js';

   console.log(greeting);  // Output: Hello
  1. Module Paths:
    Module paths specify the location of the module files. They can be relative (e.g., './module1.js') or absolute, depending on your project structure.
  2. Strict Mode by Default:
    Modules are implicitly in strict mode, providing a more secure and less error-prone environment. Variables need to be explicitly declared with const, let, or var.
  3. Top-Level Code Execution:
    Code at the top level of a module is executed only once, preventing unintended side effects. This is in contrast to scripts, where code is executed every time the script is loaded.

Modules have become a standard and widely adopted feature in modern JavaScript development. They promote code organization, reusability, and maintainability by encapsulating functionality within well-defined boundaries. They are especially useful in larger projects where code can be distributed across multiple files and modules, making the overall structure more manageable.

Module in javascript is a piece of reusable code that can easily be used into
other JavaScript files

JavaScript modules are stored in separate files, one file per module. There are two
options when creating and exporting a module: you can export multiple JavaScript
objects from a single module, or one JavaScript object per module

Example of ES6 module

/text-helpers.js

export const print(message) => log(message, new Date())
export const log(message, timestamp) =>
console.log(`${timestamp.toString()}: ${message}`}

export default can be used in place of export when you wish to export only one
type. Again, both export and export default can be used on any JavaScript type:
primitives, objects, arrays, and functions

Example

./mt-freel.js

const freel = new Expedition("Mt. Freel", 2, ["water", "snack"])
export default freel

Modules can be consumed in other JavaScript files using the import statement. Modules with multiple exports can take advantage of object destructuring. Modules that use export default are imported into a single variable

Example

import { print, log } from './text-helpers'
import freel from './mt-freel'
print('printing a message')
log('logging a message')
freel.print()

we can scope module variables locally under different variable names

import { print as p, log as l } from './text-helpers'
p('printing a message')
l('logging a message')

Table of Contents

CommonJS

CommonJS is the module pattern that is supported by all versions of Node.js. we can still use these modules with Babel and webpack. With CommonJS, JavaScript
objects are exported using module.exports

Example:

./txt-helpers.js

const print(message) => log(message, new Date())
const log(message, timestamp) =>
 console.log(`${timestamp.toString()}: ${message}`}
module.exports = {print, log}

CommonJS does not support an import statement. Instead, modules are imported with the require function

Example:

const { log, print } = require('./txt-helpers')

Leave a Comment