2

Trying to do something relatively simple. I've 2 LWC component under the lwc folder: lwc/cmp1 and lwc/cmp2

How can I create a new ES6 module that will serve as a utils.js file and then import it to each of cmp1 and cmp2?

I tried creating the utils.js file on cmp1 folder but couldn't import it to cmp2. Tried creating a new folder under lwc folder but it still didn't work (can't import).

The error I keep on getting is:

force-app/main/default/lwc/utils/utils.js  LWC1011: Failed to resolve import "../utils/utils" from "cmp1.js". Please add "../utils/utils" file to the component folder.

There is no problem with the path given, VSCode easily find the related path and indicates no errors, only when trying to deploy to Salesforce

1
  • 1
    can you show relative code? Aug 20, 2019 at 14:38

2 Answers 2

12

You should not use "../utils/utils" for imports from modules. It should be 'c/utils'.

Implementation:

Create utils module:

sfdx force:lightning:component:create --type lwc -n utils -d force-app/main/default/lwc

Delete utils.html file.

Put below code in utils.js:

// mortage.js
const getTermOptions = () => {
    return [
        { label: '20 years', value: 20 },
        { label: '25 years', value: 25 },
    ];
};

const calculateMonthlyPayment = (principal, years, rate) => {
    // Logic
};

export { getTermOptions, calculateMonthlyPayment };

Now deploy this module:

sfdx force:source:deploy -p force-app/main/default/lwc/utils

Now, in your component cmp1 which is already created and deployed, import above utils module like below:

import { getTermOptions, calculateMonthlyPayment } from 'c/utils';

Now, you can use getTermOptions() inside the class of cmp1.js file.

5

you need to create service component (component without *.html file).

Here is the example from documentation.

Your utils file.

// mortgage.js
const getTermOptions = () => {
    return [
        { label: '20 years', value: 20 },
        { label: '25 years', value: 25 },
    ];
};

const calculateMonthlyPayment = (principal, years, rate) => {
    // Logic
};

export { getTermOptions, calculateMonthlyPayment };

Your import statement in cmp1 or cmp2.

import { getTermOptions, calculateMonthlyPayment } from 'c/mortgage';

For more information follow LWC documentation provided earlier and spec for import statements.

Hopefully, that will help.

You must log in to answer this question.

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