[SalesForce] Cannot import a component inside another component in lwc

I have my main component (cmp1) and another 3 other components (helpers/services, they dont have html, only js).
In cmp1 I'm calling helper1 that calls helper2

cmp1->helper1->helper2

helper1 throws error

helper2.initializeContext is not a function

Im importing with import {initializeContext} from 'c/helper2' notation and helper2 have lwc class structure but helper1 dont (its similar to mortgage.js, only methods with export).

I've tried to import with but still not working

import initializeContext from '../helper2/helper2.js'

Helper2

    import { LightningElement, api, wire, track } from "lwc";

export default class sheetHelper extends LightningElement {
    @api context;`

    initializeContext(parentsContext) {
        this.context = parentsContext;
    }

Helper1

    import { initializecontext } from 'c/helper2';
    function initialize(parentsContext) {
        initializeContext(parentsContext); <-throw error
        ...
    }
    ...
    export { initialize }

Main component

import { initialize } from 'c/helper1';

export default class PedidosExcelDealer extends LightningElement {

    renderedCallback() {
        initialize(this.template);
    }
}

Best Answer

To define and import a value or function the code to import would look e.g. like this:

// Reason enum
const Reason = Object.freeze({
    ADOPTION: { name: 'adoption', label: 'Adoption/foster care'},
    BEREAVEMENT: {name: 'bereavement', label: 'Bereavement'},
    ...
});

const reasonFromName = (name) => {
    return Object.values(Reason).find(value => value.name === name);
};

export {
    Reason,
    reasonFromName
};

and you could import it and use it e.g. like this:

import { LightningElement, api } from 'lwc';
import { reasonFromName } from 'c/shared';

export default class IntakeReason extends LightningElement {

    @api reason;

    change(event) {
        this.reason = reasonFromName(event.target.value);
        this.dispatchEvent(new CustomEvent('reason'));
    }
}

In your code, the initializeContext method is a class method i.e. only makes sense via an instance of a LightningElement.

You could use inheritance, but note this from the Salesforce documentation:

Inheritance is allowed, but it isn’t recommended because composition is usually more effective. To share logic between components, use a module that contains only logic. See Additional JavaScript Files for Sharing Code. If you do choose to use inheritance, note that it doesn’t work across namespaces.

Related Topic