Skip to content
javascript

How to export multiple files in JavaScript

Jun 25, 2023Abhishek EH2 Min Read
How to export multiple files in JavaScript

In this tutorial, we will learn how to export multiple files in JavaScript. We will be using the export and module.exports to export multiple files in JavaScript.

Export using the export keyword

Consider the following example:

utils.js
1function add(a, b) {
2 return a + b
3}
4
5function subtract(a, b) {
6 return a - b
7}

We can export these 2 functions as follows:

utils.js
1function add(a, b) {
2 return a + b
3}
4
5function subtract(a, b) {
6 return a - b
7}
8
9export { add, subtract }

We can also export by adding the export keyword before the function declaration as follows:

utils.js
1export function add(a, b) {
2 return a + b
3}
4
5export function subtract(a, b) {
6 return a - b
7}

These functions can be imported in another file as follows:

main.js
1import { add, subtract } from "./utils.js"

Using module.exports in non ES6 environments

If you have a non ES6 environment like Node.js, you can use module.exports to export multiple files in JavaScript.

utils.js
1function add(a, b) {
2 return a + b
3}
4
5function subtract(a, b) {
6 return a - b
7}
8
9module.exports = { add, subtract }

These functions can be imported in another file as follows:

main.js
1const { add, subtract } = require("./utils.js")

That's it. We have learned how to export multiple files in JavaScript using export and module.exports.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com