Table of Contents
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 + b3}45function subtract(a, b) {6 return a - b7}
We can export these 2 functions as follows:
utils.js
1function add(a, b) {2 return a + b3}45function subtract(a, b) {6 return a - b7}89export { 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 + b3}45export function subtract(a, b) {6 return a - b7}
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 + b3}45function subtract(a, b) {6 return a - b7}89module.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