3

Is it possible to extend multiple lighting base web components?

Something like this:

import externalScripts from 'c/Scripts';
import { LightningElement, api } from 'lwc';

export default class Topics extends LightningElement, externalScripts{
    @api name;
}

I want to use @track, @api but they are not working

Thanks!

2 Answers 2

8

That's not possible for prototypical inheritance. But you can use Mix-Ins to emulate multiple inheritances:

Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

let calculatorMixin = Base => class extends Base {
  calc() { }
};

let randomizerMixin = Base => class extends Base {
  randomize() { }
};

A class that uses these mix-ins can then be written like this:

class Foo { }
class Bar extends calculatorMixin(randomizerMixin(Foo)) { }

Some additional resources: Mixins for Web Components

0

A good practice is also checking if the passed class to mixin is an instance of Lightning Element.

Edit:

function assertIsLightningElementSubclass(Base) {
    const baseProto = Base.prototype;

    if (typeof baseProto.dispatchEvent !== 'function') {
        throw new TypeError(`${Base} must be an Element type`);
    }
}

You are more than welcome to check this: https://beyondthecloud.dev/blog/mixins-in-lwc-dreamforce-2022 out and use it as a base for your mixins.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .