Categories
JavaScript Answers

How to import module with a variable name in Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *