w3resource

Re-exporting in JavaScript Modules for better code management


Re-exporting:

Write a JavaScript module that re-exports functions from another module.

Solution-1:

JavaScript Code:

File: mathOperations.js

// --- file: mathOperations.js ---
// Export individual functions
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

File: advancedMath.js

// --- file: advancedMath.js ---
// Re-export functions from mathOperations.js
export { add, subtract } from './mathOperations.js';

// Add additional exports
export function multiply(a, b) {
  return a * b;
}

File: app.js

// --- file: app.js ---
// Import re-exported and additional functions
import { add, subtract, multiply } from './advancedMath.js';

// Use the imported functions
console.log(add(10, 5));         // Output: 15
console.log(subtract(10, 5));    // Output: 5
console.log(multiply(10, 5));    // Output: 50

Output:

15
5
50

Explanation:

  • 'mathOperations.js' defines and exports 'add' and 'subtract' functions.
  • 'advancedMath.js' re-exports 'add' and 'subtract' from 'mathOperations.js' and adds its own 'multiply' function.
  • 'app.js' imports all functions seamlessly, benefiting from re-exporting to keep the module structure clean.

Solution-2:

JavaScript Code:

File: stringOperations.js

// --- file: stringOperations.js ---
// Export individual string utility functions
export function toUpperCase(str) {
  return str.toUpperCase();
}

export function toLowerCase(str) {
  return str.toLowerCase();
}

File: textUtils.js

// --- file: textUtils.js ---
// Re-export all exports from stringOperations.js
export * from './stringOperations.js';

// Add an additional export
export function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

File: main.js

// --- file: main.js ---
// Import re-exported and additional functions
import { toUpperCase, toLowerCase, capitalize } from './textUtils.js';

// Use the imported functions
console.log(toUpperCase('hello'));   // Output: HELLO
console.log(toLowerCase('WORLD'));   // Output: world
console.log(capitalize('javaScript')); // Output: Javascript

Output:

HELLO
world
Javascript

Explanation:

  • 'stringOperations.js' defines and exports 'toUpperCase' and 'toLowerCase'.
  • 'textUtils.js' re-exports all exports from 'stringOperations.js' using 'export *' syntax and adds a new 'capitalize' function.
  • 'main.js' imports everything from 'textUtils.js', demonstrating how re-exporting simplifies and centralizes module management.

Improve this sample solution and post your code through Disqus

Previous: Mastering Default and Named Exports in JavaScript Modules.
Next: Import Aliases in JavaScript Modules.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.