Renaming Exports and Imports

Sometimes, you may not want to use the original name of a variable, function, or class you’ve imported from a module. Fortunately, you can change the name of an export both during the export and during the import.

In the first case, suppose you have a function that you’d like to export with a different name. You can use the as keyword to specify the name that the function should be known as outside of the module:

  1. function sum(num1, num2) {
  2. return num1 + num2;
  3. }
  4. export { sum as add };

Here, the sum() function (sum is the local name) is exported as add() (add is the exported name). That means when another module wants to import this function, it will have to use the name add instead:

  1. import { add } from "./example.js";

If the module importing the function wants to use a different name, it can also use as:

  1. import { add as sum } from "./example.js";
  2. console.log(typeof add); // "undefined"
  3. console.log(sum(1, 2)); // 3

This code imports the add() function using the import name and renames it to sum() (the local name). That means there is no identifier named add in this module.