DAY 13 - Understanding JavaScript Modules
Screenshot:-

JavaScript modules are a way to structure and organize code, making it more manageable, reusable, and maintainable. This guide will take you through creating, exporting, and importing modules, as well as using third-party modules and module bundling. By the end, you'll have a solid grasp of how to work with modules in JavaScript.
1. Creating and Exporting Modules
Modules allow you to encapsulate code and export it for use in other scripts.
Task 1: Creating a Module to Add Two Numbers
First, create a file named math.js with the following content:
// math.js
function add(a, b) {
return a + b;
}
module.exports = add;
Next, create another file app.js to import and use the add function:
// app.js
const add = require('./math');
const sum = add(3, 5);
console.log(`Sum: ${sum}`);
Task 2: Creating a Module to Represent a Person
Create a file named person.js with the following content:
// person.js
const person = {
name: 'John Doe',
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}`);
},
};
module.exports = person;
Then, create another file app.js to import and use the person object:
// app.js
const person = require('./person');
console.log(person.name);
person.greet();
2. Named and Default Exports
Named exports allow you to export multiple values from a module, while default exports allow you to export a single value.
Task 3: Using Named Exports
Create a file named utils.js with the following content:
// utils.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
Then, create another file app.js to import and use these functions:
// app.js
import { add, subtract } from './utils';
console.log(`Add: ${add(3, 5)}`);
console.log(`Subtract: ${subtract(9, 4)}`);
Task 4: Using Default Export
Create a file named defaultExport.js with the following content:
// defaultExport.js
export default function greet(name) {
console.log(`Hello, ${name}`);
}
Then, create another file app.js to import and use this function:
// app.js
import greet from './defaultExport';
greet('Alice');
3. Importing Entire Modules
Sometimes, it's useful to import an entire module as an object.
Task 5: Importing Entire Module as an Object
Create a file named constants.js with the following content:
// constants.js
export const PI = 3.14;
export const E = 2.71;
export function circleArea(radius) {
return PI * radius * radius;
}
export function naturalLogarithm(x) {
return Math.log(x) / Math.log(E);
}
Then, create another file app.js to import and use the entire module:
// app.js
import * as constants from './constants';
console.log(`PI: ${constants.PI}`);
console.log(`Area: ${constants.circleArea(5)}`);
console.log(`Log: ${constants.naturalLogarithm(10)}`);
4. Using Third-Party Modules
Third-party modules can be installed via npm and used in your projects.
Task 6: Using lodash
First, install lodash using npm:
npm install lodash
Create a file app.js to import and use lodash:
// app.js
import _ from 'lodash';
const array = [1, 2, 3, 4, 5];
console.log(_.shuffle(array));
Task 7: Using axios
First, install axios using npm:
npm install axios
Create a file app.js to import and use axios:
// app.js
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});
5. Module Bundling (Optional)
Module bundlers like Webpack or Parcel allow you to bundle multiple JavaScript files into a single file.
Task 8: Using Webpack
First, install Webpack and its CLI:
npm install --save-dev webpack webpack-cli
Create a webpack.config.js file:
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
Create a src/index.js file:
// src/index.js
import { add, subtract } from './utils';
console.log(`Add: ${add(3, 5)}`);
console.log(`Subtract: ${subtract(9, 4)}`);
Then, run Webpack:
npx webpack --config webpack.config.js
Conclusion and Additional Resources
By mastering modules, you can write cleaner, more modular JavaScript code. Modules help organize your code, making it easier to maintain and reuse. For further reading, check out these resources:
Node.js Modules
Webpack Documentation
About the author
I am a passionate web developer and open-source enthusiast on a captivating journey of coding wonders. With a year of experience in web development, my curiosity led me to the enchanting world of React, where I found a true calling. Embracing the magic of collaboration and knowledge-sharing, I ventured into the realm of open source, contributing to Digital Public Goods (DPGs) for the betterment of the digital universe. A firm believer in learning in public, I share my insights and discoveries through blogging, inspiring fellow coders to embark on their own magical coding odysseys. Join me on this thrilling adventure, where imagination and technology converge, and together, let's shape the future of the digital landscape! 🎩✨
Comments
Join the discussionNo comments yet. Be the first to comment.