I was trying to define a class in a module as a singleton. It seems that this is the default behaviour of this plugin, thanks to the caching. To test this, I added a log message to the class's constructor, which I expected to see only once.
Say that this is my module:
class MyClass {
constructor() {
console.log('Class instance created');
}
}
const classInstance = new MyClass();
modules.export = { classInstance };
If I use the same class instance under different names with multiple imports:
const { classInstance: a } = await self.require.import('module.js');
const { classInstance: b } = await self.require.import('module.js');
// Do stuff with `a` and `b`
The constructor is invoked once as expected. Same with multiple imports with self.require(). However, if I use both patterns (because sometimes I can't use await and need to use self.require()), the constructor is invoked exactly twice. The use of the await keyword with either import method has no impact. This is true across multiple notes or within the same note.
const { classInstance: a } = await self.require.import('module.js');
const { classInstance: b } = await self.require('module.js');
// Do stuff with `a` and `b`
// Constructor is invoked twice
I was trying to define a class in a module as a singleton. It seems that this is the default behaviour of this plugin, thanks to the caching. To test this, I added a log message to the class's constructor, which I expected to see only once.
Say that this is my module:
If I use the same class instance under different names with multiple imports:
The constructor is invoked once as expected. Same with multiple imports with
self.require(). However, if I use both patterns (because sometimes I can't useawaitand need to useself.require()), the constructor is invoked exactly twice. The use of theawaitkeyword with either import method has no impact. This is true across multiple notes or within the same note.