Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 19, 2024 09:21 pm GMT

Understanding Modules in JavaScript: Comparing require and ES6 Imports

1. require

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 numbersfunction add(a, b) {    return a + b;}// Function to subtract two numbersfunction subtract(a, b) {    return a - b;}// Export the functionsmodule.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 moduleconst math = require('./mathOperations');// Using functions from the mathOperations moduleconst sum = math.add(10, 5);const difference = math.subtract(10, 5);console.log(`Sum: ${sum}`);         // Output: Sum: 15console.log(`Difference: ${difference}`); // Output: Difference: 5

2. Import and Export

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.

Basics of Import and Export

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

Export
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.jsexport 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.jsconst greeting = () => "Hello World";export default greeting;

Import

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

Importing Named Exports

// file: calculator.jsimport { add, multiply } from './mathFunctions.js';console.log(add(2, 3));  // Output: 5console.log(multiply(2, 3));  // Output: 6

Importing Default Exports

// file: app.jsimport 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: 9console.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.jsexport const addUser = (name) => `Added user: ${name}`;export default function() { return "Fetching all users"; }
// file: app.jsimport 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 moduleimport('./mathFunctions.js')  .then(math => {    console.log(math.add(5, 10));  })  .catch(err => console.log(err));

Original Link: https://dev.to/vimuth7/understanding-modules-in-javascript-comparing-require-and-es6-imports-11ec

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To