Feasibility to import entire LWC classes to access @api methods

I am not ES6+ or JS expert, but there's a section for this on the documentation - Share JavaScript Code and also there are examples on lwc-recipe for this. In general, the export works as documented for ES6 module.

From LWC documentation:

A module can export a single default function or variable.

A module can also export named functions or variables.

So it doesn't seem that you can actually export the whole class. You will need to modify your shared JS based on the approach as mentioned in the documentation, i.e., you will need to export the functions as named functions. For further details, refer to the links mentioned above.


As a quick example, below is an approach for exporting and using a named function.

Let's say I have a shared JS as below:

sharedJS.js

const mySharedHelloWorld = () => {
     return 'Hello Shared World!'; 
}

export {mySharedHelloWorld};

And that I want to use this on another component, I will go doing as below in the component.

helloWorldJS.js

import { mySharedHelloWorld} from 'c/sharedJS';

export default class MyHelloWorld extends LightningElement {

    myHelloWorld = mySharedHelloWorld();
}

helloWorld.html

{myHelloWorld}

Okay, so, I was thinking about this and I couldn't find a way to expose a whole Javascript class in another component, but I did come up with a clever little bit of "syntactic sugar" to make it work like we all want. Since the import only allows methods or variables, I simply created a const variable which was an object, whose properties are the class methods. Then, I only had to export/import that variable and voila! Now we can access them like they're classes.

someService.js

const foo = () => {
     return 'foo'; 
}
const bar = () => {
     return 'bar';
}
const SomeService = {
      foo: foo,
      bar: bar,
}

export {SomeService};

app.js

import { SomeService} from 'c/someService';

export default class App extends LightningElement {

    myFoo = SomeService.foo();
    myBar = SomeService.bar();
}

app.html

<template>
{myFoo} {myBar}
</template>

Now, it's not exactly the same thing as importing a whole Javascript Class, but, it works in similar ways. I tested it and methods in the Service class can call on each other, so "Private" methods are simply methods that aren't included in the "SomeService" object. Also, you can add other vars as you like, to that object, and now you can use it just like an External Service Class.

Please feel free to improve on my answer, here's the Playground Link: https://developer.salesforce.com/docs/component-library/tools/playground/bT9aPFeTv