Javascript - Module Renaming Identifiers

Introduction

ES6 allows you to rename exports and imports using the as keyword.

function sum(a, b) { 
    return a + b; 
} 

export { sum as add }; 

Here, sum is the local name of the exported function.

But the function is exported as add and needs to be imported in another module using its exported name add.

import { add } from "./moduleFIle.js"; 

To use a different name when you import the identifier, use the following way,

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

Here, the exported name add is imported as sum.

You can rename an identifier to default to make it a default export.

function multiply(a, b) { 
    return a * b; 
} 

export { multiply as default }; 

You can import defaults after renaming them as well:

import { default as multiply, message } from "moduleFile.js"; 

console.log(multiply(1, 2));      // 2 
console.log(message);             // "42 is the answer to the everything." 

Since default is a keyword in JavaScript, it cannot otherwise be used as a variable, function, or class name.

Related Topic