How to Import and Export Modules in ESM using Node
Table of Contents
With the introduction of ES modules to ECMA Script, the JavaScript community has been able to use the import and export keywords to import and export modules.
This is JavaScript's way to standardize the way we break up our code into modules and import them into other modules.
Node has historically used the CommonJS module system, which uses the require keyword to import modules and the module.exports keyword to export modules.
However, Node has recently added support for ES modules, which means we can now use the import and export keywords to import and export modules.
In this post, we'll learn how to use the import and export keywords to import and export modules in Node.
How to export modules in Node
To export modules in Node, we use the export keyword.
Let's export a function that does simple addition. Create a file called addition.js
and add the following code:
JAVASCRIPTconst addition = (a, b) => a + b;
export default addition;
That's it, we've exported a function that adds two numbers.
How to import modules in Node
To import modules in Node, we use the import keyword.
Let's import the addition function we exported in the previous section. Create a file called index.js
and add the following code:
JAVASCRIPTimport addition from "./addition.js";
console.log(addition(1, 2));
Now, if your Node project supports ESM, you should get the following when you try and run the index.js
file:
BASH3
It's really that simple, we've exported and then imported the addition function and used it to add two numbers.
Conclusion
In this post, we learned how to use the import and export keywords to import and export modules in Node.
Simply use the export keyword to export a function or variable and then use the import keyword to import the function or variable into another module.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Using Axios to Pull Data from a REST API