9

I am trying to import modules dynamically in my LWC component.

While pushing the change I get a strange error LWC1509: This experimental syntax requires enabling the parser plugin: 'dynamicImport'

Here is sample code that produces the error

calculator/calculator.js

export default class Calculator {
    static add = (a, b) =>  a + b;
}

sample/sample.js

import { LightningElement } from 'lwc';
// import Calculator from "c/calculator";

export default class Sample extends LightningElement {
    connectedCallback() {
        import("c/calculator")
        .then(Calculator => alert(Calculator.add(1, 2)))
        .catch(error => console.error(error));
    }
}

I could't find any documentation which mentions dynamic import is not supported in LWC.

Google redirects me to a github issue raised for babel. Is this a limitation with LWC or am I missing something?

1
  • 4
    I think dynamic imports are used only for dynamic instantiation of components. See this RFC. I've used the lwc:dynamic syntax in LWC OSS projects and as far as I know it's not yet available inside of Salesforce. I think you are getting an error meant to show only in LWC OSS. Commented Jul 1, 2020 at 13:23

3 Answers 3

0

Could you please try

export Calculator {
    static add = (a, b) =>  a + b;
}

without the default/class keyword. Worked for me.

0

You can create a LWC only with the XML by default and the JS.

In the JS you export what you want, for example:

export function getQueryParameters() {
...
}
export function whateverFunction(){
...
}

this LWC is called jsUtilities, and the code only has this functions.

Then, when you want to import, you have to use the syntax like this:

import { getQueryParameters, whateverFunction } from 'c/jsUtilities';

And to use it just don't use this.getQueryParameters() but just the name of the function:

renderedCallback(){
        if(!this.initialized){
            let urlParams = getQueryParameters();
...
0

Do you have below in the meta.xml file for the LWC?

<capabilities>
    <capability>lightning__dynamicComponent</capability>
</capabilities>

Also, here is some sample code you can reference for dynamic components.

import { LightningElement, api } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { reduceErrors } from "c/ldsUtils";
const VIEW_MAPPING = {
    card: () => import("c/accountContactsCardView"),
    table: () => import("c/accountContactsTableView")
};
export default class AccountContacts extends LightningElement {
    // Public properties
    @api recordId;
    /** Component constructor that allows for importing the dynamic component */
    componentConstructor;
    /** The default component view */
    view = "card";
    // Private properties
    _isLoading;

    get viewOptions() {
        return [
            { label: "Card", value: "card" },
            { label: "Table", value: "table" }
        ];
    }

    get isLoading() {
        return this._isLoading;
    }

    /**
    * Imports the default component
    */
    async connectedCallback() {
        this._isLoading = true;
        try {
            const { default: ctor } = await import("c/accountContactsCardView");
            this.componentConstructor = ctor;
        } catch (error) {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: "Component Load Error",
                    message: reduceErrors(error).join(", "),
                    variant: "error",
                    mode: "pester",
                })
            );
        } finally {
            this._isLoading = false;
        }
    }

    /**
    * Sets the view which determines what component to display
    * @param {Object} event the change event
    */
    handleChange(event) {
        this._isLoading = true;
        this.view = event.detail.value;
        VIEW_MAPPING[this.view]().then(({ default: ctor }) => {
            this.componentConstructor = ctor;
        }).catch((error) => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: "Component Load Error",
                    message: reduceErrors(error).join(", "),
                    variant: "error",
                    mode: "pester",
                })
            );
        }).finally(() => {
            this._isLoading = false;
        });
    }
}

Template

<template>
    <div class="slds-m-around_medium">
        <lightning-card title="Contacts" icon-name="standard:contact">
            <lightning-combobox
                name="contactsView"
                label="Contacts View"
                value={view}
                placeholder="Select Contacts View"
                options={viewOptions}
                onchange={handleChange}
            ></lightning-combobox>
        </lightning-card>
    </div>
    <div lwc:if={isLoading} class="slds-is-relative">
        <lightning-spinner alternative-text="Loading..." variant="brand"> </lightning-spinner>
    </div>
    <lwc:component
        ref="contactsView"
        record-id={recordId}
        lwc:is={componentConstructor}
    ></lwc:component>
</template>

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.