Home Javascript, module.exports in chapter 10 of "Eloquent Javascript"
Reply: 1

Javascript, module.exports in chapter 10 of "Eloquent Javascript"

Vadim Anisimov
1#
Vadim Anisimov Published in 2018-01-09 14:55:41Z

Here is the code:

   function require(name) {
  if (name in require.cache)
    return require.cache[name];

  var code = new Function("exports, module", readFile(name));
  var exports = {}, module = {exports: exports};
  code(exports, module);

  require.cache[name] = module.exports;
  return module.exports;
}
require.cache = Object.create(null); 

What is the role of this require.cache object? And why can't exports variable hold a function, for example? Because the author of the book tells us that we can not export a function, for example, into this variable.

As far as I can see, bot export and module.export will (and actually can) hold the same kind of data.

Thank you!

Axnyff
2#
Axnyff Reply to 2018-01-09 15:04:36Z

The cache is used to avoid re-requiring something, this is used in the first line of the require, otherwise, you have to actually read the file.

That line: var exports = {}, module = {exports: exports};

make it that exports and module.exports refer to the same object.

There is no reason that you couldn't not export a function though, what is the actual wording of the author?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.40081 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO