1

I'm trying to understand why require works while import does not for an npm package. The package is r7insight_node and allows us to send our logs to their product, Rapid7. When we use require as per their instructions things work fine, but don't when I use import.

Their library has an src/index.js file that looks like:

//  Use codependency for dynamically loading winston
const requirePeer = codependency.register(module);

//  Import winston
const winston = requirePeer('winston', {optional: true});
const Transport = requirePeer('winston-transport', {optional: true});

//  If we have successfully loaded winston (user has it)
//  we initialize our InsightTransport
if (winston) {
  provisionWinston(winston, Transport);
}

//  Logger is default export
module.exports = Logger;
//  Export as `bunyanStream` to not break existing integration
module.exports.bunyanStream = buildBunyanStream;
module.exports.provisionWinston = provisionWinston;

My understanding is that require is synchronous and is "computed" whereas import is asynchronous and is NOT "computed" as written here. Is this the reason for why require works while import does not?

Does "computed" mean in that the index.js file is executed and hence the if (winston) block is checked and executed in a require but not in an import? Is there a way to achieve the same using import statements?

Thanks in advance

n00b
  • 5,843
  • 11
  • 52
  • 82
  • 1
    For a module to work with `import`, it has to be designed to be compatible with `import` and the caller has to import it the right way. Modules designed for `require()` are NOT automatically compatible with `import`. – jfriend00 Jul 23 '20 at 00:43

1 Answers1

2

for the package to work with the ES6 import way, it has to be written to it, it has to be exported as eg:export default Logger and not module.exports = Logger, hope my answer helped you

Martin Munilla
  • 302
  • 4
  • 8