JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to re-export values from another file in JavaScript?

You might be wondering why do you need to re-export already exported values. Well, re-export from a single file helps you to import all the required values with just one import statement. This concept is used in React router, where you re-export all the page components from Index.js file and then import all the components in App.js.

Let's understand how to re-export values with the help of an example:

Suppose you have 2 files, and each file exports one function. So, instead of importing these two files separately, you re-export all the functions from one file.

//sum.js
export function sum(a, b){
  return a + b;
}

//multiply.js
function multiply(a, b){
  return a * b;
}
index.js
export {sum} from './sum.js';
export {multiply} from './multiply.js';

Explanation of the code:

  • In this example, you have two files sum.js and multiply.js.
  • sum.js file exports sum() function and multiply.js file exports multiply() function.
  • index.js re-exports sum() and multiply() functions.

You re-export the named exports like this:

export {myClass, myConstant, myFunction} from './file.js';

The default export is re-exported in this way:

export {default} from './file.js';

You cannot use these functions in index.js because you haven't imported. You have re-exported them.

index.js
export {sum} from './sum.js';
export {multiply} from './multiply.js';

console.log(sum(3, 4)); //error
console.log(multiply(3, 4)); //error

Here is how you import the re-exported functions.

app.js
import {sum, multiply} from './index.js';

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

Recommended Posts