Mastering import all as alias in JavaScript
Import all as Alias:
Write a JavaScript programme that imports all exports from a module as a single object and use its properties.
Solution-1:
JavaScript Code:
File: utilities.js
// --- file: utilities.js ---
// Export multiple utility functions
export function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function reverse(str) {
return str.split('').reverse().join('');
}
export function toLowerCase(str) {
return str.toLowerCase();
}
File: app.js
// --- file: app.js ---
// Import all exports as an alias
import * as utils from './utilities.js';
// Use the imported properties
console.log(utils.capitalize('hello')); // Output: Hello
console.log(utils.reverse('world')); // Output: dlrow
console.log(utils.toLowerCase('TEST')); // Output: test
Output:
Hello dlrow test
Explanation:
- 'utilities.js' exports multiple functions.
- 'app.js' imports all functions as a single object using `import * as alias` syntax.
- The 'utils' alias groups all the exported functions, allowing them to be accessed as properties of the object.
Solution-2:
JavaScript Code:
File: mathUtils.js
// --- file: mathUtils.js ---
// Export mathematical utility functions
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;
export const divide = (a, b) => (b !== 0 ? a / b : 'Cannot divide by zero');
File: main.js
// --- file: main.js ---
// Import all exports as an alias
import * as math from './mathUtils.js';
// Use the imported properties
console.log(math.add(5, 3)); // Output: 8
console.log(math.subtract(5, 3)); // Output: 2
console.log(math.multiply(5, 3)); // Output: 15
console.log(math.divide(5, 0)); // Output: Cannot divide by zero
Output:
8 2 15 Cannot divide by zero
Explanation:
- 'mathUtils.js' exports several mathematical utility functions.
- 'main.js' imports all the functions as a single object using 'import * as alias' syntax.
- The 'math' alias encapsulates all the exported functions, which can be accessed as properties of the 'math' object.
- This approach makes it easy to organize and access related functions under one namespace.
Improve this sample solution and post your code through Disqus
Previous: Named Exports in JavaScript for Arithmetic Operations.
Next: Mastering Default and Named Exports 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