We use the as
keyword to rename the code that we export.
// module-1.js// Define a variable named "bestClub":const bestClub = "Your Club";// Export the bestClub variable as "favoriteTeam":export { bestClub as favoriteTeam };
In the snippet above, we tell the computer to export the bestClub
variable as favoriteTeam
. Therefore, when importing the variable, we’ll use the name favoriteTeam
— not bestClub
.
Let’s look at an example of this below.
// module-2.jsimport { favoriteTeam } from "./module-1.js";const myBestClub = favoriteTeam + " " + "is my best club.";console.log(myBestClub);
We can rename multiple exports by separating each as
statement with a comma.
// module-1.js// Define two variables:const bestClub = "Your Club";const fruits = ["Grape", "Apple", "Pineapple", "Lemon"];// Define a function:function multiply(x, y) {return x * y;}// Export the three statements above:export {bestClub as favoriteTeam,fruits as crops,multiply as product};
In the snippet above, we tell the computer to export the bestClub
variable as favoriteTeam
, the fruits
variable as crops
, and the multiply
function as product
. Therefore, when importing the statements, you will use favoriteTeam
, crops
, and product
.
Let’s look at an example of this below.
// module-2.jsimport { favoriteTeam, crops, product } from "./module-1.js";const bestClub = `I bought ${product(2, 11)} ${crops[2]}s at ${favoriteTeam}.`;console.log(bestClub);
Use the as
keyword to rename the code we import.
// module-2.js// Import the bestClub variable as favoriteTeam:import { bestClub as favoriteTeam } from "./module-1.js";const myBestClub = favoriteTeam + " " + "is my best club.";console.log(myBestClub);
In the snippet above, we told tell the computer to import the bestClub
variable as favoriteTeam
.
We can rename multiple imports by separating each as
statement with a comma.
// module-2.js// Import the bestClub, fruits, and multiply variables as favoriteTeam, crops, and product:import {bestClub as favoriteTeam,fruits as crops,multiply as product} from "./module-1.js";// Define a variable named "bestClub":const bestClub = `I bought ${product(2, 11)} ${crops[2]}s at ${favoriteTeam}.`;// Display the bestClub variable's content on the browser's console:console.log(bestClub);
The choice of whether to rename our code during export or import is totally up to us.
However, many developers prefer to rename during import because we don’t always have control over a code’s source file, especially when importing from a third party’s module.
Free Resources