JavaScript Modules using Namespace Imports
Namespace Import:
Write a JavaScript program that imports an entire module as a namespace and access its properties.
Solution 1: Using Namespace Import for Utility Functions
Code:
File: mathUtils.js
This file contains multiple utility functions exported individually..
// mathUtils.js
// Exporting multiple utility functions
export const add = (a, b) => a + b; // Adds two numbers
export const subtract = (a, b) => a - b; // Subtracts two numbers
export const multiply = (a, b) => a * b; // Multiplies two numbers
export const divide = (a, b) => a / b; // Divides two numbers
File: main.js
This file demonstrates importing the entire module as a namespace.
// main.js
// Importing the entire module as a namespace
import * as MathUtils from './mathUtils.js';
// Accessing properties of the namespace
console.log(MathUtils.add(10, 5)); // Logs 15
console.log(MathUtils.multiply(4, 3)); // Logs 12
Output:
15 12
Explanation:
- mathUtils.js exports four utility functions using named exports.
- In main.js, the entire module is imported as a namespace MathUtils.
- The namespace provides access to all exported functions, which can be used with the MathUtils prefix.
Solution-2: Using Namespace Import for Constants and Functions
Code:
File: constants.js
This file contains constants and utility functions exported individually.
// constants.js
// Exporting constants
export const PI = 3.14159;
export const E = 2.718;
// Exporting utility functions
export const circleArea = (radius) => PI * radius * radius; // Calculates area of a circle
export const exponential = (base, power) => Math.pow(base, power); // Calculates exponentiation
File: main.js
This file demonstrates importing the entire module as a namespace.
// main.js
// Importing the entire module as a namespace
import * as Constants from './constants.js';
// Accessing constants and functions from the namespace
console.log(Constants.PI); // Logs 3.14159
console.log(Constants.circleArea(5)); // Logs 78.53975 (area of a circle with radius 5)
console.log(Constants.exponential(2, 3)); // Logs 8 (2 raised to the power 3)
Output:
3.14159 78.53975 8
Explanation:
- constants.js exports constants (PI and E) and utility functions (circleArea and exponential).
- In main.js, the entire module is imported as a namespace Constants.
- The namespace is used to access both constants and utility functions.
Improve this sample solution and post your code through Disqus
Previous: JavaScript: Using Custom Aliases for Default Exports.
Next: Handle Circular dependencies in JavaScript Modules.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics