This content originally appeared on Go Make Things and was authored by Go Make Things
Late last year, I wrote about ES modules: how to import
and export
them, and how to define a default export.
One thing I didn’t mention is that ES modules provide a simple way to rename variables and functions when importing and exporting them. You might want to do this to avoid naming conflicts, or simple for convenience.
Today, let’s dig into how that works.
Worth mentioning: I’m working on a new Pocket Guide to ES Modules. Today’s article is an excerpt from it.
Renaming an import
Let’s say you have a helpers.js
module that exports a getTheAnswer()
function.
function getTheAnswer () {
return 42;
}
export {getTheAnswer};
But in your index.js
where you’re going to import it, you already have a function with that name.
// This is a problem because getTheAnswer() is already in this module
import {getTheAnswer} from './helpers.js';
// Tell them the total
function getTheAnswer () {
alert(`The answer is ${getTheAnswer()}`);
}
getTheAnswer();
Fortunately, you can rename function when you import
it using the as
operator: import {importedFunction as newFunctionName}
.
// Rename the import
import {getTheAnswer as answer} from './helpers.js';
// Tell them the total
function getTheAnswer () {
alert(`The answer is ${answer()}`);
}
getTheAnswer();
Now, the getTheAnswer()
function from helpers.js
is assigned to the answer
variable, and will not conflict with the existing function.
Renaming an export
ES modules also allow you to rename a function or variable while exporting it, again use the as
syntax: export {exportedFunction as newFunctionName}
.
In our helpers.js
file, for example, we can rename getTheAnswer
to answer
on export
.
function getTheAnswer () {
return 42;
}
export {getTheAnswer as answer};
Then, in the index.js
file, we can import
the function as answer
.
import {answer} from './helpers.js';
// Tell them the total
function getTheAnswer () {
alert(`The answer is ${answer()}`);
}
getTheAnswer();
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2021-03-10T15:30:00+00:00) Renaming imports and exports with ES modules in vanilla JS. Retrieved from https://www.scien.cx/2021/03/10/renaming-imports-and-exports-with-es-modules-in-vanilla-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.