Import Aliases in JavaScript Modules
Import with Alias:
Write a JavaScript programme that imports named exports from a module using alias names and use them in another file.
Solution-1: Using ES6 Module Syntax
JavaScript Code:
File: mathUtils.js
// mathUtils.js
// Exporting functions from mathUtils.js
export const add = (a, b) => a + b; // Adds two numbers
export const subtract = (a, b) => a - b; // Subtracts two numbers
File: main.js
// main.js
// Importing named exports with alias
import { add as sum, subtract as difference } from './mathUtils.js';
// Using the imported functions with their aliases
console.log(sum(5, 3)); // Logs the sum of 5 and 3
console.log(difference(5, 3)); // Logs the difference of 5 and 3
Output:
8 2
Explanation:
- The add and subtract functions are exported from mathUtils.js.
- These functions are imported into main.js with alias names (sum and difference).
- The aliases are used to call the functions, making the code more descriptive or better aligned with the current context.
Solution-2: Using CommonJS Syntax
JavaScript Code:
File: mathUtils.js
// mathUtils.js
// Exporting functions using CommonJS syntax
exports.add = (a, b) => a + b; // Adds two numbers
exports.subtract = (a, b) => a - b; // Subtracts two numbers
File: main.js
//main.js
// Importing named exports with alias
const { add: sum, subtract: difference } = require('./mathUtils.js');
// Using the imported functions with their aliases
console.log(sum(10, 7)); // Logs the sum of 10 and 7
console.log(difference(10, 7)); // Logs the difference of 10 and 7
Output:
17 3
Explanation:
- The add and subtract functions are exported using CommonJS syntax (exports).
- In main.js, these functions are imported and renamed using object destructuring with aliases (sum and difference).
- The renamed aliases are then used in the script.
Improve this sample solution and post your code through Disqus
Previous: Re-exporting in JavaScript Modules for better code management.
Next: Dynamic Imports 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