Ben Aston
Ben Aston

Reputation: 55779

Does 'module.exports' have to be syntactically located inside the file containing the export?

Does module.exports have to be syntactically located inside the file containing the export?

For example, if I define a global function property myDefine that attempts to perform the module.exports assignment from inside itself, will this work.

If not, why not?

file1.js

GLOBAL.myDefine = function(fn) {
  module.exports = fn;
};

file2.js

require('./file1');
myDefine(function() {
  return function MyExport() {};
});

Upvotes: 1

Views: 38

Answers (1)

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

When Node requires file, it wraps the contents in an outer function:

function(exports, require, module, __filename, __dirname){

}

When file1.js gets interpreted, the module.exports = fn will reference its own local module instance, hence it will have no impact on file2.js. In order to get this to work, you'd need to somehow pass file2.js module instance to file1's myDefine() e.g.

file1.js

GLOBAL.myDefine = function(module, fn) {
  module.exports = fn;
}

file2.js

require('./file1');
myDefine(module, function() {
  return function MyExport() {};
});

Upvotes: 1

Related Questions