Understanding Modules in JavaScript: Comparing require and ES6 Imports
Published: 2024-04-19 21:21:29

## <u>1. require</u>

This is supported only in backend nodejs. Not supported in browsers.

Let's look at a simple example using the require function in a Node.js environment. We will create a basic module that performs arithmetic operations and then import this module in another file using require.

### Step 1: Create the Module
First, let's create a module file called mathOperations.js that will export some simple arithmetic functions.

```
// File: mathOperations.js

// Function to add two numbers
function add(a, b) {
    return a + b;
}

// Function to subtract two numbers
function subtract(a, b) {
    return a - b;
}

// Export the functions
module.exports = {
    add,
    subtract
};

```

### Step 2: Import and Use the Module
Next, create another file called app.js where we will import and use the functions from the mathOperations.js module.


```
// File: app.js

// Importing the mathOperations module
const math = require('./mathOperations');

// Using functions from the mathOperations module
const sum = math.add(10, 5);
const difference = math.subtract(10, 5);

console.log(`Sum: ${sum}`);         // Output: Sum: 15
console.log(`Difference: ${difference}`); // Output: Difference: 5
```

---


## <u>2. Import and Export</u>

import and export statements in JavaScript, which are part of the ES6 module system. This system provides a standard way to modularize JavaScript code and manage dependencies between files.

### <u>Basics of Import and Export</u>

In ES6 modules, code and functionality are organized into separate files, and import and export are used to access functionality across these files.

<u>**Export**</u>
There are two types of exports:

**Named Exports**: Useful for exporting multiple values from a module. Each export can be imported with the same name enclosed in curly braces.

```
// file: mathFunctions.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
```

**Default Exports**: Each module can have one default export, which is useful for when a module exports a single value or a primary functionality.

```
// file: defaultExport.js
const greeting = () => "Hello World";
export default greeting;
```

**<u>Import</u>**

To use the exported functionalities in another file, you would use import:

**Importing Named Exports**

```
// file: calculator.js
import { add, multiply } from './mathFunctions.js';

console.log(add(2, 3));  // Output: 5
console.log(multiply(2, 3));  // Output: 6
```

**Importing Default Exports**

```
// file: app.js
import greeting from './defaultExport.js';

console.log(greeting());  // Output: "Hello World"
```

### Advanced Usage

**Renaming Imports**: If you want to avoid naming conflicts or prefer a different name, you can rename imports:

```
import { add as addNumbers } from './mathFunctions.js';

console.log(addNumbers(5, 3));  // Output: 8
```

**Importing Everything**: To import all exports from a module as an object, you can use:


```
import * as MathFuncs from './mathFunctions.js';

console.log(MathFuncs.add(7, 2));  // Output: 9
console.log(MathFuncs.multiply(7, 2));  // Output: 14
```

**Renaming Both Named and Default Exports**: 

Consider a module that exports both named and default exports, and you want to import and rename them in another file:

```
// file: userOperations.js
export const addUser = (name) => `Added user: ${name}`;
export default function() { return "Fetching all users"; }
```

```
// file: app.js
import fetchUsers, { addUser as createUser } from './userOperations.js';

console.log(fetchUsers()); // Output: "Fetching all users"
console.log(createUser('John')); // Output: "Added user: John"
```

**Dynamic Imports**: ES6 modules also support dynamic imports using the import() function, which returns a promise. This is useful for lazy-loading modules.

```
// Lazy load a module
import('./mathFunctions.js')
  .then(math => {
    console.log(math.add(5, 10));
  })
  .catch(err => console.log(err));
```