skip to Main Content

I have an existing common.js file that exports only one object from it. As a result, another existing some_other_file_1.js file includes the line const common = require('common') and is able to use that export.

I would like to modify common.js to export additional objects, without having to modify some_other_file_1.js. Those additional objects will be used by other files. What is the syntax for that?


My current code:

some_other_file_1.js (I must not modify this file)

const common = require('common')

const foo = () => {
  common.dostuff()
}

common.js (the file I want to modify)

const common = {
  dostuff: () => {
    // code I've omitted
  },
}

const cool_func = () => {
  // code I've omitted
}

module.exports = common
// >>> I wish to also export cool_func <<<

2

Answers


  1. To export additional objects from your common.js file without modifying some_other_file_1.js, you can create a new object that combines both common and cool_func and export that new object. Here’s how you can do it:

    common.js (modified):

    const common = {
    
    dostuff: () => {
        // code I've omitted
      },
    };
    
    const cool_func = () => {
      // code I've omitted
    };
    
    // Create a new object that combines common and cool_func
    const combinedExports = {
      common,
      cool_func,
    };
    
    module.exports = combinedExports;
    

    Now, some_other_file_1.js can still use the common object as it did before, and other files can access cool_func as follows:

    some_other_file_1.js (unchanged):

    const common = require('common');
    
    const foo = () => {
      common.dostuff();
    };
    

    Another_file.js (or any other file that wants to use cool_func):

    const common = require('common');
    
    common.cool_func(); // You can now use cool_func
    

    By creating the combinedExports object in common.js, you can export both the original common object and the new cool_func function without modifying the importing code in some_other_file_1.js.

    Login or Signup to reply.
  2. Assign the named export as a property

    You could assign the new export as a property on your current export.

    For example:

    // common.js
    
    const common = {
      doStuff: () => {
        /* ... */
      }
    };
    
    const cool_func = () => {
      /* ... */
    };
    
    common.cool_func = cool_func;
    
    module.exports = common;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search