JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to export all functions from a file using JavaScript?

If you have more than functions in a file and want to make them available to other files, use named export. There are two different ways of using named export:

1. You write the export keyword before the function declaration.

utils.js
export function add(a, b){
  return a + b;
}
export function multiply(a, b){
  return a * b;
}

2. You export all functions as an object.

utils.js
function add(a, b){
  return a + b;
}
function multiply(a, b){
  return a * b;
}
export {add, multiply};

Here is how you import the exported functions.

app.js
import { add, multiply } from './utils.js';

console.log(add(3, 4)); //7

console.log(multiply(3, 4)); //12

An alternative way is to export one of the functions as default and the remaining functions as named export.

utils.js
export default function add(a, b){
  return a + b;
}
export function multiply(a, b){
  return a * b;
}

By removing the curly braces, you import the default exported function. Conversely, named exported functions are imported using the curly braces.

app.js
import add, { multiply } from './utils.js';

console.log(add(3, 4)); //7

console.log(multiply(3, 4)); //12

Recommended Posts