Skip to content

self.require and self.require.import of class instances invoke class constructors separately #45

Description

@aaandreeew

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions