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.

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that imports a default export using a custom alias and calls the function using that alias.
  • Write a JavaScript program that renames a default export to a more descriptive name during import and logs its output.
  • Write a JavaScript program that imports a default function as an alias and demonstrates its usage in a simple calculation.
  • Write a JavaScript program that validates the output of a default import alias by comparing it to the original function’s return value.

Go to:


PREV : Tree Shaking.
NEXT :Namespace Import.

Improve this sample solution and post your code through Disqus

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.