Skip to content

import/export classes on javascript

I’m exporting a class into my main code, But I’m not able to use any function of it. Including my singleton pattern function to instance it.

index.js :

import __system from '../crud-js/system.js';

const s = __system.getInstance();

system.js :

export default  class system{

motoboys = [];
clientes = [];
static INSTANCE = new system();
constructor() {
    
}

getInstance(){
    return INSTANCE;
}

error :

const s = __system.getInstance();
                   ^

TypeError: __system.getInstance is not a function
    at file:///home/mkyy/Desktop/cursojs/crud-js/index.js:4:20
    at ModuleJob.run (node:internal/modules/esm/module_job:197:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:337:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)

Node.js v17.5.0

Answer

getInstance is written as an instance method in your class, but you are trying to call it as a static method.

Instead do this:

static get instance() {
    return system.INSTANCE;
}

and use it like this:

const s = __system.instance;