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
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):
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):
Another_file.js (or any other file that wants to 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.
Assign the named export as a property
You could assign the new export as a property on your current export.
For example: