Sometimes, we want to import module with a variable name in Node.js.
In this article, we’ll look at how to import module with a variable name in Node.js.
How to import module with a variable name in Node.js?
To import module with a variable name in Node.js, we can call the import
function.
For instance, we write
const importModule = async () => {
try {
const module = await import("./path/module.js");
} catch (error) {
console.error("import failed");
}
};
to call import
with the path string to the module.
It returns a promise with the module that we imported.
So we get the module
with await
.
Conclusion
To import module with a variable name in Node.js, we can call the import
function.