Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
45 views
in Technique[技术] by (71.8m points)

javascript - NodeJS behavior of exporting class object

I am trying to understand the behavior of exporting class object instead of class name. Please help me make understand. Example

class Util {
  method() {
    return "method";
  }
}

module.exports = new Util();

and then importing it like

import Util from 'Util';
question from:https://stackoverflow.com/questions/65887632/nodejs-behavior-of-exporting-class-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I want to understand, how many times the object will be created?

Once, in the normal case. Modules are loaded and cached, and if they're imported by multiple other modules, those modules all see the same instance of the module doing the exporting.

When using CJS modules, the cache is require.cache and you can clear a module from the cache by deleting the property for it from the require.cache object, meaning that it will get loaded fresh the next time it's require'd. (I don't think it's possible to do that with ESM modules.)


Note: You're mixing CJS (module.exports =...) and ESM (import). I suggest you pick one and use it consistently, not least because you can't use require to import an ESM module.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...