w3resource

Learn to Dynamically Override JavaScript Module Exports


Overriding Exports:

Write a JavaScript program to create a module and override its exports dynamically in another file.

In JavaScript, overriding exports means modifying or replacing the exported values from a module dynamically in another file. This can be useful for testing, mocking, or extending functionality.

Solution 1: Overriding with Custom Exports

Code:

File: moduleA.js

This file defines the initial exports.

// moduleA.js
 // Exporting an object with default properties
export const config = {
  mode: 'production',
  debug: false,
};

// Exporting a function
export function logMessage(message) {
  if (config.debug) {
    console.log(`[DEBUG] ${message}`);
  } else {
    console.log(message);
  }
}

File: main.js

This file overrides the config object dynamically.

//main.js
// Importing the module
import { config, logMessage } from './moduleA.js';

// Overriding the exported config object
config.debug = true; // Enabling debug mode

// Using the overridden export
logMessage('This is a debug message.');  

Output:

[DEBUG] This is a debug message.

Explanation:

  • moduleA.js exports an object (config) and a function (logMessage).
  • In main.js, the config object is imported and its debug property is modified.
  • The change dynamically affects the behavior of the logMessage function.

Solution-2: Overriding Exports by Mocking

Code:

File: moduleB.js

This file defines a simple exported function.

// moduleB.js
 // Exporting a function
export function fetchData() {
  return 'Real data from the server';
}

File: main.js

This file overrides the fetchData function dynamically.

// main.js
// Importing the module
import { fetchData as originalFetchData } from './moduleB.js';

// Creating a wrapper for fetchData
let fetchData = originalFetchData;

// Overriding the fetchData function dynamically
fetchData = function () {
  return 'Mock data for testing';
};

// Using the overridden export
console.log(fetchData()); // Logs "Mock data for testing" 

Output:

Mock data for testing

Explanation:

  • Immutable Imports: The original fetchData from moduleB.js is imported and stored as originalFetchData.
  • Wrapper: A new local variable fetchData acts as a wrapper that can be reassigned or mocked.
  • Overriding Locally: The wrapper function (fetchData) is overridden without modifying the original module export.
  • Mock Implementation: The overridden version is used as needed without affecting the immutability of ES6 imports.

Improve this sample solution and post your code through Disqus

Previous: Import JavaScript Modules for Side Effects.
Next: Practical Guide to Mixing ES6 and CommonJS 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.