Assignments Of Day 25: JavaScript Modules and NPM
Assignment
1: Creating and Using ES Modules
1. Task: Create
two ES modules, one for utility functions and another for main functionality.
Use import and export to share and use these functions.
o
Create a utilities.js file that contains functions
for:
§ Adding
two numbers.
§ Finding
the maximum number in an array.
o
Create a main.js file to import and use these
functions.
Solution:
utilities.js
javascript
Copy code
export function
addNumbers(a, b) {
return a + b;
}
export function
findMax(array) {
return Math.max(...array);
}
main.js
javascript
Copy code
import {
addNumbers, findMax } from './utilities.js';
console.log("Sum:",
addNumbers(10, 20)); // Output: Sum: 30
console.log("Max:",
findMax([10, 20, 30, 40])); // Output: Max: 40
Run the main.js using a browser
or Node.js. Ensure to include the file extension .js when importing modules.
Assignment
2: Installing and Using NPM Packages
2. Task:
o
Initialize a new project using npm init.
o
Install the axios package to fetch data from an
API.
o
Use it to make a GET request to the JSONPlaceholder
API (https://jsonplaceholder.typicode.com/posts/1).
o
Print the response to the console.
Solution:
Step 1: Initialize the Project
bash
Copy code
npm init
-y
Step 2: Install Axios
bash
Copy code
npm
install axios
Step 3: Create app.js
javascript
Copy code
const
axios = require('axios');
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log("Post Title:",
response.data.title);
})
.catch(error => {
console.error("Error fetching
data:", error);
});
Step 4: Run the Script
bash
Copy code
node
app.js
Output:
text
Copy code
Post
Title: sunt aut facere repellat provident occaecati excepturi optio
reprehenderit
Assignment
3: Creating a Script Using a Third-Party Package
3. Task:
o
Install the chalk package to style console output.
o
Write a script that:
§ Prints a
success message in green.
§ Prints an
error message in red.
§ Prints a
warning message in yellow.
Solution:
Step 1: Install Chalk
bash
Copy code
npm
install chalk
Step 2: Create styles.js
javascript
Copy code
const
chalk = require('chalk');
console.log(chalk.green('Success!
Operation completed.'));
console.log(chalk.red('Error!
Something went wrong.'));
console.log(chalk.yellow('Warning!
Check your input.'));
Step 3: Run the Script
bash
Copy code
node
styles.js
Output:
Styled messages in the terminal with appropriate colors.
Assignment
4: Refactoring Code Using Modules
4. Task:
o
Write a script with two modules:
§ mathOperations.js:
Contains functions for addition, subtraction, multiplication, and division.
§ main.js:
Imports the functions and demonstrates their usage.
Solution:
mathOperations.js
javascript
Copy code
function add(a,
b) {
return a + b;
}
function subtract(a,
b) {
return a - b;
}
function multiply(a,
b) {
return a * b;
}
function divide(a,
b) {
return b !== 0 ? a / b : 'Cannot divide by
zero';
}
module.exports
= { add, subtract, multiply, divide };
main.js
javascript
Copy code
const {
add, subtract, multiply, divide } = require('./mathOperations');
console.log("Addition:",
add(10, 5)); // Output: Addition:
15
console.log("Subtraction:",
subtract(10, 5)); // Output: Subtraction: 5
console.log("Multiplication:",
multiply(10, 5)); // Output: Multiplication: 50
console.log("Division:",
divide(10, 5)); // Output:
Division: 2
Run the main.js file using
Node.js.
Assignment
5: Managing Dependencies in package.json
5. Task:
o
Initialize a project and add three packages (lodash,
moment, chalk).
o
Write a script that:
§ Formats a
date using moment.
§ Capitalizes
a string using lodash.
§ Prints the
output using chalk.
Solution:
Step 1: Initialize Project and Install Packages
bash
Copy code
npm init
-y
npm
install lodash moment chalk
Step 2: Create dependencies.js
javascript
Copy code
const _ =
require('lodash');
const
moment = require('moment');
const
chalk = require('chalk');
const
formattedDate = moment().format('MMMM Do YYYY, h:mm:ss a');
const
capitalizedString = _.capitalize('hello world');
console.log(chalk.blue('Formatted
Date:'), chalk.green(formattedDate));
console.log(chalk.blue('Capitalized
String:'), chalk.green(capitalizedString));
Step 3: Run the Script
bash
Copy code
node
dependencies.js
Output:
Displays the formatted date and capitalized string with styled colors in the
console.
Let me know if you need
additional assignments or variations on these concepts!
4o
You said:
give more
ChatGPT
said:
ChatGPT
Additional
Assignments: JavaScript Modules and NPM
Assignment
6: Dynamic Imports in ES Modules
1. Task:
o
Create a module named mathUtils.js with a function square(n)
that returns the square of a number.
o
Dynamically import this module in main.js based on
a condition (e.g., user input).
Solution:
mathUtils.js
javascript
Copy code
export function
square(n) {
return
n * n;
}
main.js
javascript
Copy code
const
userInput = true;
if
(userInput) {
import('./mathUtils.js')
.then(module => {
console.log("Square of
5:", module.square(5)); // Output: Square of 5: 25
})
.catch(err => {
console.error("Error loading
module:", err);
});
}
Step 3: Run main.js in a modern
browser or Node.js
bash
Copy code
node
main.js
Assignment
7: Version Locking in NPM
2. Task:
o
Install lodash version 4.17.21 in a project.
o
Write a script using lodash’s _.reverse() function
to reverse an array.
o
Lock the lodash version in your package.json using npm
shrinkwrap.
Solution:
Step 1: Install Specific Version of Lodash
bash
Copy code
npm
install lodash@4.17.21
Step 2: Write reverseArray.js
javascript
Copy code
const _ =
require('lodash');
const
array = [1, 2, 3, 4];
console.log("Original
Array:", array);
console.log("Reversed
Array:", _.reverse(array));
Step 3: Lock Dependencies
bash
Copy code
npm
shrinkwrap
Step 4: Run the Script
bash
Copy code
node
reverseArray.js
Assignment
8: NPM Scripts Automation
3. Task:
o
Write an NPM script in the package.json file that
runs a custom JavaScript file (app.js).
o
The script should be named start-app.
o
Use the script to run the file.
Solution:
Step 1: Add Script in package.json
json
Copy code
{
"scripts": {
"start-app": "node
app.js"
}
}
Step 2: Create app.js
javascript
Copy code
console.log("Welcome
to the Custom App!");
Step 3: Run the Script
bash
Copy code
npm run
start-app
Output:
text
Copy code
Welcome
to the Custom App!
Assignment
9: Managing Dev Dependencies
4. Task:
o
Install eslint as a development dependency.
o
Add a linting configuration file.
o
Write a script to lint your code using eslint.
Solution:
Step 1: Install ESLint
bash
Copy code
npm
install eslint --save-dev
Step 2: Initialize ESLint
bash
Copy code
npx
eslint --init
Step 3: Add a Script in package.json
json
Copy code
{
"scripts": {
"lint": "eslint ."
}
}
Step 4: Run the Linting Script
bash
Copy code
npm run
lint
Assignment
10: Creating a Local Node Module
5. Task:
o
Create a local Node.js module named mathOperations.
o
Use it in another script to perform addition and
subtraction.
Solution:
Step 1: Create mathOperations.js
javascript
Copy code
module.exports
= {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
};
Step 2: Create main.js
javascript
Copy code
const
math = require('./mathOperations');
console.log("Addition
of 10 and 5:", math.add(10, 5)); // Output: 15
console.log("Subtraction
of 10 and 5:", math.subtract(10, 5)); // Output: 5
Step 3: Run the Script
bash
Copy code
node
main.js
Assignment
11: Uninstalling NPM Packages
6. Task:
o
Install the moment package.
o
Use it in a script to print the current date.
o
Uninstall the package and verify it’s removed.
Solution:
Step 1: Install Moment
bash
Copy code
npm
install moment
Step 2: Create date.js
javascript
Copy code
const
moment = require('moment');
console.log("Current
Date:", moment().format('YYYY-MM-DD'));
Step 3: Run the Script
bash
Copy code
node
date.js
Step 4: Uninstall Moment
bash
Copy code
npm
uninstall moment
Verify Removal
Check node_modules folder and package.json to confirm removal.
Assignment
12: Publishing a Custom Package
7. Task:
o
Create a package named my-utils.
o
Add a utility function for greeting a user.
o
Publish it to a local NPM registry.
Solution:
Step 1: Create and Initialize Package
bash
Copy code
mkdir
my-utils
cd
my-utils
npm init
-y
Step 2: Add Utility Function
index.js
javascript
Copy code
exports.greet
= (name) => `Hello, ${name}!`;
Step 3: Test Locally
bash
Copy code
npm link
cd
../project-folder
npm link
my-utils
Test Script:
javascript
Copy code
const utils
= require('my-utils');
console.log(utils.greet("Alice"));
// Output: Hello, Alice!
