w3resource

JavaScript: Using Custom Aliases for Default Exports


Default Import Alias:

Write a JavaScript program to import a default export using a custom name and invoke it.

Solution 1:

Code:

File: greet.js

This file contains a default export for a greeting function.

// greet.js
// Defining and exporting a default function
export default function greet(name) {
  return `Hello, ${name}!`; // Returns a greeting message
}

File: main.js

This file imports the default export using an alias.

// main.js  
// Importing the default function using an alias
import sayHello from './greet.js';

// Invoking the imported function
console.log(sayHello('Rosaire'));

Output:

Hello, Rosaire!

Explanation:

  • greet.js defines and exports a default function named greet.
  • In main.js, the default export is imported using the alias sayHello.
  • The alias sayHello is invoked, and the function's behavior is demonstrated.

Solution-2: Default Export Class with Alias

Code:

File: Calculator.js

This file contains a default export for a class.

// Calculator.js
// Defining and exporting a default class
export default class Calculator {
  add(a, b) {
    return a + b; // Adds two numbers
  }

  subtract(a, b) {
    return a - b; // Subtracts two numbers
  }
}

File: main.js

This file imports the default class using an alias.

// main.js  
// Importing the default class using an alias
import MathTool from './Calculator.js';

// Instantiating the imported class and using its methods
const calculator = new MathTool();
console.log(calculator.add(5, 3)); // Logs 8
console.log(calculator.subtract(10, 6)); // Logs 4  

Output:

8
4

Explanation:

  • Calculator.js defines and exports a default class named Calculator.
  • In main.js, the default export is imported using the alias MathTool.
  • The alias MathTool is used to create an instance of the class and access its methods.

Improve this sample solution and post your code through Disqus

Previous: JavaScript Modules with Tree Shaking Techniques.
Next:JavaScript Modules using Namespace Imports.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.