6

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.
    – adriancg
    Jul 1 '20 at 13:23
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();
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.